namespace System.ComponentModel{//// Summary:// Notifies clients that a property value has changed.public interface INotifyPropertyChanged{//// Summary:// Occurs when a property value changes.event PropertyChangedEventHandler? PropertyChanged;}}
public class Person{private string name = String.Empty;public string Name{get{return name;}set{this.name = value;}}}
<Grid><Grid.RowDefinitions><RowDefinition></RowDefinition><RowDefinition></RowDefinition></Grid.RowDefinitions><TextBox Grid.Row="0" Grid.Column="0" Height="30" Width="200"Text="{Binding Path=Name}" ></TextBox><Button x:Name="btnChangeProperty" Width="100" Height="50" Grid.Row="1" Grid.Column="0"Click="btnChangeProperty_Click">更改属性</Button></Grid>
public partial class MainWindow : Window{Person person = new Person();public MainWindow(){InitializeComponent();person.Name = "桂兵兵";this.DataContext = person;}private void btnChangeProperty_Click(object sender, RoutedEventArgs e){person.Name = "桂素伟";}
通过上面的例子我们看到TextBox中的值并没有发生变化
我们让Person来实现INotifyPropertyChanged接口,依然是上面的例子
public class Person : INotifyPropertyChanged{private string name = String.Empty;public string Name{get{return name;}set{if (value != this.name){this.name = value;NotifyPropertyChanged();}}}public event PropertyChangedEventHandler? PropertyChanged;private void NotifyPropertyChanged([CallerMemberName] String propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}}
当我们看到通过按钮改变实体类属性的时候,页面绑定的值也改变了,这个就是INotifyPropertyChanged接口起到的效果