INotifyPropertyChanged 接口用于向客户端(通常是执行绑定的客户端)发出某一属性值已更改的通知。
当绑定数据源的某属性值改变时,它可以通知客户端,并进行界面数据更新.而我们不用写很多复杂的代码来更新界面数据,这样可以做到方法简洁而清晰,INotifyPropertyChanged确实是一个强大的接口。
首先,我们需要了解如下有关Silverlight 2.0 数据绑定的术语:
Binding - 将绑定目标对象的属性与数据源联接起来
Source - 绑定的数据源
Mode - 绑定的数据流的方向 [System.Windows.Data.BindingMode枚举]
BindingMode.OneTime - 一次绑定。创建绑定时一次性地更新绑定目标对象的属性
BindingMode.OneWay - 单向绑定(默认值)。数据源的改变会自动通知到绑定目标对象的属性
BindingMode.TwoWay - 双向绑定。数据源或绑定目标对象的属性的值发生改变时会互相通知。显然,做数据验证的话一定要是双向绑定
INotifyPropertyChanged - 向客户端发出某一属性值已更改的通知
IValueConverter - 值转换接口,将一个类型的值转换为另一个类型的值。它提供了一种将自定义逻辑应用于绑定的方式
public class User: INotifyPropertyChanged // 类
{
private string _Name;
public string Name
{
get { return this._Name; }
set
{
this._Name = value;
notifyPropertyChanged("Name");
}
}
private bool sex;
public bool Sex
{
get { return sex; }
set
{
sex = value;
notifyPropertyChanged("Sex");
}
}
private int _Age;
public int Age
{
get { return this._Age; }
set
{
this._Age = value;
notifyPropertyChanged("Age");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void notifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" >
<DockPanel >
<Grid Height="300" Width="300" Background="#FFDE3030">
<TextBlock Text="姓名:" Margin="42,38,130,237" />
<TextBox x:Name="tbName" Width="100" Height="30" Margin="107,35,93,235" Text="{Binding Name, Mode=TwoWay}" />
<TextBlock Text="年龄:" Margin="42,69,199,204" TextTrimming="None" />
<TextBox x:Name="tbAge" Width="100" Height="30" Margin="107,66,93,204" Text="{Binding Age,Mode=TwoWay}"/>
<CheckBox x:Name="cbxSex" Content="性别" IsChecked="{Binding Sex,Mode=TwoWay}" Height="16" HorizontalAlignment="Left" Margin="224,35,0,0" VerticalAlignment="Top" Width="62" />
</Grid>
</Window>
/// <summary>
/// MainWindow.xaml 后台代码 /// </summary>
public partial class MainWindow : Window
{
User Myuser = new User();
public MainWindow()
{
InitializeComponent();
Myuser = new User();
Myuser.Name = "刘李杰";
Myuser.Age = 23;
tbName.DataContext = Myuser;
tbAge.DataContext = Myuser;
cbxSex.DataContext = Myuser;
Myuser.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Myuser_PropertyChanged);
}
void Myuser_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
MessageBox.Show(e.PropertyName.ToString()+"改变");
}