2010-12-21 123 views
0

为什么点击按钮后文本块中的文本不会改变?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 
} 

回答

1
<TextBlock Text="{Binding Name}"/> 

在上面的代码绑定属性Name文本框和下面的代码:

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    MyPerson = new Person { Name = "B" }; 
} 

你设定MyPerson给新人。

这是打算? Person类实现INotifyPropertyChanged事件吗?

您只更新MyPerson属性。 DataContext仍具有对对象的引用,您创建使用下面一行:

MyPerson = new Person { Name = "A" }; 
在构造

。您还需要更新DataContext

相反,使用下面的代码:

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    MyPerson = new Person { Name = "B" }; 
    DataContext = MyPerson; 
}  
+0

不会更改点击上的datacontext会对性能产生影响吗?不应该使用相同的数据上下文对象。也许将其作为类成员并在Person类上实现INotifyPropertyChanged以通知“Name”成员上的更改。然后,而不是说MyPerson =新人{名称=“B”};如果让Person对象的类成员为mPerson那么说,mPerson.Name =“B”。 – whoisthis 2010-12-21 10:43:34

+1

嗯,我在答复中提到过。但OP没有就此回复。我仍然建议亲自实施'INotifyPropertyChanged'并更改它的'Name'属性,而不是创建一个全新的'Person'对象。 – decyclone 2010-12-21 10:49:38

+0

谢谢!澄清 – whoisthis 2010-12-21 11:30:23

0

您需要实现Person类INotifyPropertyChanged的,然后就改变MyPerson提高的PropertyChanged,这个名字,如果你希望它是清洁...

或者,你可以重新申请已创建到DataContext新创建的对象,否则将无法正常工作

1

变化

<TextBlock Text="{Binding Name}"/> 

<TextBlock Text="{Binding MyPerson, Path=Name}"/> 

既然你绑定到名称,NotifyPropertyChanged不会被上名称当你改变MyPerson解雇和视图不会被更新。