WPF-18 INotifyPropertyChanged 接口

我们先来看看微软官方给出的定语:通知客户端属性值已经更改。其实对于一个陌生小白来说,很难通过这句话来理解其中的原理,这个接口在WPF和Winform编程中经常会用到,下面是该接口的定义:.
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;    }}
我们通过一个简单的例子对比来理解一下它具体作用,我们定义一个普通的Person类,该类没有实现INotifyPropertyChanged接口
 public class Person {        private string name = String.Empty;        public string Name        {            get            {                return name;            }            set            {                this.name = value;            }        }    }
接下来我们用WPF来实现一个简单的绑定,页面加载的时候在文本框中默认绑定Person属性,我们通过一个按钮来改变对象的属性,来查看文本框中的值是否发生变化
  <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接口起到的效果

通俗点讲,当我们绑定一个对象属性的时候,如果该对象实现了INotifyPropertyChanged接口,数据绑定会订阅该接口中的事件,当属性发生变化的时候,会通知到数据绑定!