INotifyPropertyChanged 不会导致此代码中的屏幕更新 [英] INotifyPropertyChanged not causing screen update in this code

查看:41
本文介绍了INotifyPropertyChanged 不会导致此代码中的屏幕更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码基于此帖子:

我的问题:在这个简单示例中,我看不到让 INotifyPropertyChanged 导致 textBox1 绑定自动反映更改的错误.

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.我添加了 textBox2 以确认属性正在更改

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>

代码隐藏

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.

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.

推荐答案

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

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

DataContext = New ViewModel() 

应该是:

DataContext = vm

这篇关于INotifyPropertyChanged 不会导致此代码中的屏幕更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆