我知道我在这里做错了什么,但是什么。请看看并指出我的错误。INotifyPropertyChanged.PropertyChanged始终为NULL
我会在我的文本框中看到“Peter”,但点击按钮后没有“Jack”。
我班
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");
}
}
谢谢。
有两个人(一个或多个)。 TextBox绑定到来自Grid资源的Person,而Button则从Private域设置Person的Name。我认为你应该使用一个Person作为Window的DataContext。这将澄清你的代码和标记。 – 2011-04-22 10:15:05
您可能想要阅读[this](http://msdn.microsoft.com/en-us/library/ms752347.aspx)&[this](http://msdn.microsoft.com/en-us/library /ms750613.aspx),因为你在绑定和资源方面有些混乱。 – 2011-04-22 13:28:28