wpf - INotifyPropertyChanged 不会导致此代码中的屏幕更新

标签 wpf vb.net mvvm

下面的代码基于此 post :

我的问题:在这个简单的示例中,我看不出我做错了什么来让 INotifyPropertyChanged 导致 textBox1 绑定(bind)自动反射(reflect)更改。

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

View 模型

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。

最佳答案

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

DataContext = New ViewModel() 

应该是:

DataContext = vm

关于wpf - INotifyPropertyChanged 不会导致此代码中的屏幕更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43686740/

相关文章:

c# - Windows Presentation Foundation (WPF) 项目不支持控件

wpf - Avalonia Ui 相当于 ImageResource

wpf - 为什么我无法从代码中设置 SolidColorBrush 资源值?

c# - WPF ListView : Changing ItemsSource does not change ListView

vb.net - 包管理器 : using Enable-Migrations for a specific project in the solution

c# - Prism 5.0 在 ViewModel 中包装模型属性

c# - 是否有可能获得一个 Action 中的语句数量或确定它是否有空体?

c# - .NET 单个类的多个命名空间

Android MVVM 应用架构 : How to set up FirebaseFirestore as Repository

c# - MvvmLight EventToCommand 和 WPFToolkit DataGrid 双击