INotifyPropertyChanged does not trigger screen refresh in this code
The code below is based on this post:
My problem: I can't see what I'm doing wrong to get the INotifyPropertyChanged so that the textBox1 binding will automatically reflect the changes in this simple example.
XAML. I added textBox2 to confirm that the property was changing
<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>
CodeBehind
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
ViewModel
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
Aside from any mistake I make, any other comments on anything written that will be improved with best practice, please report; for example declaring a ViewModel or setting a StaticResource. I am learning WPF and MVVM right now.
+3
source to share