我知道我在这里做错了什么,但是什么。请大家看一下并指出我的错误。
单击按钮后,我将在文本框中看到“Peter”,但看不到“Jack”。
我的类(class)
namespace App
{
class Person : INotifyPropertyChanged
{
private string name;
public String Name
{
get { return name; }
set { name = value; OnPropertyChanged("Name"); }
}
public Person()
{
Name = "Peter";
}
public void SetName(string newname)
{
Name = newname;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string prop)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
}
我的 XAML
<Window x:Class="test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:App"
Title="MainWindow" Height="400" Width="400">
<Grid>
<Grid.Resources>
<app:Person x:Key="person"/>
</Grid.Resources>
<TextBox Width="100" Height="26" Text="{Binding Source={StaticResource person}, Path=Name, Mode=TwoWay}" />
<Button Content="Button" Height="23" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
还有我的代码隐藏
public partial class MainWindow : Window
{
Person person;
public MainWindow()
{
InitializeComponent();
person = new Person();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
person.SetName("Jack");
}
}
谢谢。
最佳答案
您有两个 Person 实例。静态资源中PropertyChanged不为null
这并不是 StaticResources 的真正用途。摆脱静态资源,将绑定(bind)更改为:
{Binding Path=Name, Mode=TwoWay}
并将其添加到您的构造函数中:
DataContext = person;
关于wpf - INotifyPropertyChanged.PropertyChanged 始终为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5754385/