INotifyPropertyChanged not causing screen update i

2019-02-25 14:09发布

问题:

The code below is based off of this post:

My problem: I can't see what I'm doing wrong to get INotifyPropertyChanged to cause the textBox1 binding to automatically reflect changes in this simple example.

XAML. I added textBox2 to confirm 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 whatever mistake I'm making, any other comments about anything written that would be improved by a best practice, please advise; such as declaring the ViewModel or setting up the StaticResource. I am learning WPF and MVVM as the same time right now.

回答1:

You aren't setting the data context to the correct ViewModel

DataContext = New ViewModel() 

Should be:

DataContext = vm


标签: wpf vb.net mvvm