数据绑定之Binding双向绑定
来源:互联网 发布:enako 知乎 编辑:程序博客网 时间:2024/05/03 06:49
Xaml代码
<!-- Binding双向绑定 --> <StackPanel Name="stackPanel" HorizontalAlignment="Left" VerticalAlignment="Top" Orientation="Vertical"> <TextBox Name="lbId" Text="{Binding ID}"/> //使用Binding绑定ID属性 <TextBox Name="lbName" Text="{Binding Name}"/> //使用Binding绑定Name属性 <TextBox Name="lbAge" Text="{Binding Age}"/> //使用Binding绑定Age属性 <Button Width="100" Height="50" Content="加1" Click="Button_Click"/> </StackPanel>
C#代码
public MainWindow() { InitializeComponent(); Init(); } StudentData stuData = new StudentData(); //实例类 public void Init() { stuData.ID = 1001; stuData.Name = "小明"; stuData.Age = 18; stuData.Name = "小明"; //this.DataContext = stuData; //整个窗口内的所有元素都可以绑定此数据 stackPanel.DataContext = stuData; //仅stackPanel内的所有元素可以绑定此数据 } //声明类 private void Button_Click(object sender, RoutedEventArgs e) { stuData.Age++; MessageBox.Show(stuData.Age.ToString()); }}//引用INotifyPropertyChanged接口,微软双向机制,通知客户端属性值已更改。public class StudentData:INotifyPropertyChanged{ private int _ID; //声明字段 private String _Name; //声明字段 private int _Age; //声明字段 public int ID { get { return _ID; } set { this._ID = value; if (PropertyChanged !=null) { PropertyChanged(this, new PropertyChangedEventArgs("ID")); //如果PropertyChanged状态改变了,响应绑定数据更新 } } } public String Name { get { return _Name; } set { this._Name = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Name")); } } } public int Age { get { return _Age; } set { this._Age = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Age")); } } } public event PropertyChangedEventHandler PropertyChanged;}
“`
阅读全文