INotifyPropertyChanged接口实现的一个小例子(2)
布局代码:
<Grid > <TextBox Height="23" Text="{Binding Name}" HorizontalAlignment="Left" Margin="22,12,0,0" Name="txtName" VerticalAlignment="Top" Width="120" /> <TextBox Height="23" Text="{Binding Age}" HorizontalAlignment="Left" Margin="33,59,0,0" Name="txtAge" VerticalAlignment="Top" Width="120"/> <TextBox Height="23" Margin="332,12,76,0" Name="textBox1" VerticalAlignment="Top" Text="{Binding Path=Value,ElementName=slider1}"/> <Slider Margin="200,50,34,191" Name="slider1" Value="{Binding Path=Text,ElementName=textBox1}" /> <Button Content="Age++" Height="23" HorizontalAlignment="Left" Margin="33,127,0,0" Name="btnAdd" VerticalAlignment="Top" Width="75" Click="btnAdd_Click" /> <Button Content="显示Age" Height="23" HorizontalAlignment="Left" Margin="145,127,0,0" Name="btnView" VerticalAlignment="Top" Width="75" Click="btnView_Click" /> </Grid>
MainWindow.xaml.cs中代码:
namespace 数据绑定 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private Person p1 = new Person(); private void Window_Loaded(object sender, RoutedEventArgs e) { p1.Name = "zhangsan"; p1.Age = 21; txtAge.DataContext = p1; txtName.DataContext = p1; } private void btnAdd_Click(object sender, RoutedEventArgs e) { p1.Age++; } private void btnView_Click(object sender, RoutedEventArgs e) { MessageBox.Show(p1.Age.ToString()); } } }
Person类中代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace 数据绑定 { class Person :INotifyPropertyChanged { //public int Age //{ // get; // set; //} //public string Name //{ // get; // set; //} private int age; private string name; public event PropertyChangedEventHandler PropertyChanged; public int Age { get { return age; } set { this.age = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Age")); } } } public string Name { get { return name; } set { this.name = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } } } }
后记:由于普通对象没有“通知我的属性变了”这么一种机制,所以改变对象的属性界面不会变。但是界面改变是有TextChanged之类的事件的,所以改变界面可以同步修改到对象。
如果要求后台对象的值发生改变界面跟着变,则需要类实现INotifyPropertyChanged接口,并且在属性值变化后触发事件:
public int Age
{
get
{
return age;
}
set
{
this.age = value;
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs("Age"));
}
}
}
如果说后台对象的值不会变,则没必要实现INotifyPropertyChanged,也能享受界面值变化DataContext对象跟着变的“福利”