【问题标题】:WPF Two controls bound to single property not updating each otherWPF 绑定到单个属性的两个控件不相互更新
【发布时间】:2013-01-27 14:42:55
【问题描述】:

我正在使用 MVVM 设计模式开发 WPF 应用程序。

我有一个 ViewModel,它通过它的基类实现 INotifyPropertyChanged。 ViewModel 包含一个属性,然后绑定到两个文本框。相关代码如下。

视图模型库

Public MustInherit Class ViewModelBase : Implements INotifyPropertyChanged
    Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
    Protected Sub onPropertyChanged(propertyName As String)
        If Not propertyName Is Nothing Then RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub
End Class

视图模型

Public Class TemplateEditVM : Inherits ViewModelBase
    Public Property Name As String
      Get
        Return _Template.Name
      End Get
      Set(value As String)
        If Not _Template.Name = value Then
          _Template.Name = value
          onPropertyChanged("TemplateEditName")
        End If
      End Set
    End Property
End Class

查看

<TextBox Text="{Binding Path=Name}" />
<TextBox Text="{Binding Path=Name}" />

第一次加载视图时,属性名称的值会正确填充两个文本框。问题是,当我更改其中一个文本框中的文本时,另一个文本框中的文本不会更改,即使基础属性已更改。如果我单步执行,我可以看到 PropertyChanged 事件正在被触发。

谁能告诉我为什么?非常感谢您的帮助。

【问题讨论】:

    标签: wpf mvvm inotifypropertychanged


    【解决方案1】:

    将绑定模式设置为双向

        <TextBox Text="{Binding Path=Name, Mode="TwoWay"}" />
    

    您的 on propertyChanged 方法应该计算出您绑定到的确切名称

    【讨论】:

    • 当然!我忘记了我已经更改了属性名称。顺便说一句,绑定不需要显式设置为 TwoWay,因为我认为这是默认设置。谢谢!
    • 是的。澄清 onPropertyChanged("TemplateEditName") 应该是 onPropertyChanged("Name") 或者必须重命名属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    相关资源
    最近更新 更多