InotifyPropertyChanged

InotifyPropertyChanged

INotifyPropertyChanged一般在数据绑定的时候使用。

InotifyPropertyChanged是.net内置的接口,数据绑定时会检测DataContext是否实现了InotifyPropertyChanged,如果实现了,就会监听PropertyChanged,得知属性变化。

可以理解为InotifyPropertyChanged接口用于向客户端发出某一属性值已更改的通知。

class Person:INotifyPropertyChanged
{
private int age;
public int Age
{
get
{
return age;
} set
{
this.age = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Age"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}

.cs文件

 public partial class MainWindow : Window
{
private Person p = new Person();
public MainWindow()
{
InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e)
{
p.Age++;
} private void Window_Loaded(object sender, RoutedEventArgs e)
{
p.Age = ;
txtAge.DataContext = p;
}
}

xaml文件

<TextBox Name="txtAge" HorizontalAlignment="Left" Height="" Margin="82,39,0,0" TextWrapping="Wrap" Text="{Binding Age}" VerticalAlignment="Top" Width=""/>
<Button Content="Age++" HorizontalAlignment="Left" Margin="271,39,0,0" VerticalAlignment="Top" Width="" Click="Button_Click"/>

传智播客--数据绑定--INotifyPropertyChanged(小白内容)-LMLPHP

这样点击button可以实现textbox里的数字自增。

04-14 10:29