石家庄网站优化推广,郑州付费系统网站开发建设,云南省文山州网站建设,怎么免费注册企业邮箱我们先来看看微软官方给出的定语#xff1a;通知客户端属性值已经更改。其实对于一个陌生小白来说#xff0c;很难通过这句话来理解其中的原理#xff0c;这个接口在WPF和Winform编程中经常会用到#xff0c;下面是该接口的定义#xff1a;namespace System.ComponentMode…我们先来看看微软官方给出的定语通知客户端属性值已经更改。其实对于一个陌生小白来说很难通过这句话来理解其中的原理这个接口在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属性我们通过一个按钮来改变对象的属性来查看文本框中的值是否发生变化GridGrid.RowDefinitionsRowDefinition/RowDefinitionRowDefinition/RowDefinition/Grid.RowDefinitionsTextBox Grid.Row0 Grid.Column0 Height30 Width200 Text{Binding PathName} /TextBoxButton x:NamebtnChangeProperty Width100 Height50 Grid.Row1 Grid.Column0 ClickbtnChangeProperty_Click更改属性/Button/Gridpublic 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接口数据绑定会订阅该接口中的事件当属性发生变化的时候会通知到数据绑定!