以下代码基于此post:
我的问题:我无法看到我做错了什么让INotifyPropertyChanged导致textBox1绑定自动反映这个简单示例中的更改。
XAML。我添加了textBox2来确认属性正在改变
<StackPanel>
<Button Margin="25" Content="Change the Value" Click="Button_Click"/>
<Label Content="{}{Binding MyTextProperty}"/>
<TextBox Name="textBox1" Text="{Binding MyTextProperty}"/>
<Label Content="updated using code behind"/>
<TextBox Name="textBox2" />
</StackPanel>
代码隐藏
Partial Class MainWindow
Private vm = New ViewModel
Sub New()
InitializeComponent()
DataContext = New ViewModel()
textBox2.Text = vm.MyTextProperty
End Sub
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
vm.ChangeTextValue()
textBox2.Text = vm.MyTextProperty
End Sub
End Class
视图模型
Public Class ViewModel
Implements INotifyPropertyChanged
Private _MyTextValue As String = String.Empty
Public Property MyTextProperty() As String
Get
Return _MyTextValue
End Get
Set(ByVal value As String)
_MyTextValue = value
NotifyPropertyChanged("MyTextProperty")
End Set
End Property
Public Sub New()
MyTextProperty = "Value 0"
End Sub
Public Sub ChangeTextValue()
MyTextProperty = Split(MyTextProperty)(0) & " " & Split(MyTextProperty)(1) + 1
End Sub
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(ByVal propertyName As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
End Class
除了我所犯的任何错误之外,还有任何其他关于通过最佳做法改进的书面评论,请指教;例如声明ViewModel或设置StaticResource。我现在正在学习WPF和MVVM。
答案 0 :(得分:6)
您没有将数据上下文设置为正确的!true == false
ViewModel
应该是:
DataContext = New ViewModel()