InotifyPropertychanged不会在此代码中引起屏幕更新



以下代码基于此帖子:

我的问题:我看不到我在做错了什么可以使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>

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

除了我犯的任何错误之外,对最佳实践所能改善的任何其他评论,请告知;例如宣布ViewModel或设置静音。我现在正在学习WPF和MVVM。

您没有将数据上下文设置为正确的ViewModel

DataContext = New ViewModel() 

应该是:

DataContext = vm

最新更新