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()+"改變");
}