为什么点击按钮后文本块中的文本不会改变?WPF - 绑定问题
XAML:
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}"/>
<Button Click="Button_Click" Grid.Row="1" Margin="20">Click Me</Button>
</Grid>
后面的代码:
public partial class Window1 : Window, INotifyPropertyChanged
{
private Person _myPerson;
public Person MyPerson
{
get { return _myPerson; }
set
{
_myPerson = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("MyPerson"));
}
}
}
public Window1()
{
MyPerson = new Person { Name = "A" };
DataContext = MyPerson;
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MyPerson = new Person { Name = "B" };
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
不会更改点击上的datacontext会对性能产生影响吗?不应该使用相同的数据上下文对象。也许将其作为类成员并在Person类上实现INotifyPropertyChanged以通知“Name”成员上的更改。然后,而不是说MyPerson =新人{名称=“B”};如果让Person对象的类成员为mPerson那么说,mPerson.Name =“B”。 – whoisthis 2010-12-21 10:43:34
嗯,我在答复中提到过。但OP没有就此回复。我仍然建议亲自实施'INotifyPropertyChanged'并更改它的'Name'属性,而不是创建一个全新的'Person'对象。 – decyclone 2010-12-21 10:49:38
谢谢!澄清 – whoisthis 2010-12-21 11:30:23