为什么 OnPropertyChanged 在代码隐藏中不起作用? [英] Why does OnPropertyChanged not work in Code Behind?
问题描述
我试图通过将 ViewModel 模型放入后面的代码并将 DataContext 绑定为this"来简化一些代码,但它的工作方式似乎有所不同,在以下示例中:
I'm trying to simplify some code by putting the ViewModel models into the code behind and binding the DataContext as "this", but it seems to work differently, in the following example:
为什么点击按钮时,绑定到Message"的TextBlock却没有变化,即使调用了OnPropertyChanged("Message")?
XAML:
<Window x:Class="TestSimple223.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel HorizontalAlignment="Left">
<Button Content="Button"
Click="button1_Click" />
<TextBlock
Text="{Binding Path=Message, Mode=TwoWay}"/>
<TextBlock
x:Name="Message2"/>
</StackPanel>
</Window>
背后的代码:
using System.Windows;
using System.ComponentModel;
namespace TestSimple223
{
public partial class Window1 : Window
{
#region ViewModelProperty: Message
private string _message;
public string Message
{
get
{
return _message;
}
set
{
_message = value;
OnPropertyChanged("Message");
}
}
#endregion
public Window1()
{
InitializeComponent();
DataContext = this;
Message = "original message";
Message2.Text = "original message2";
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Message = "button was clicked, message changed";
Message2.Text = "button was click, message2 changed";
}
#region INotify
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
推荐答案
您尚未将您的课程标记为可用于属性更改通知.把标题改成
You haven't marked your class as being available for property change notification. Change the heading to
public partial class Window1 : Window, INotifyPropertyChanged
仅仅因为您实现了方法并不意味着 WPF 知道一个类支持更改通知 - 您需要通过用 INotifyPropertyChanged 标记来告诉它.这样,绑定机制可以将您的类识别为潜在的更新目标.
Just because you implement the methods doesn't mean that WPF knows that a class supports change notification - you need to tell it by marking it with INotifyPropertyChanged. This way, the binding mechanism can identify your class as a potential update target.
这篇关于为什么 OnPropertyChanged 在代码隐藏中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!