数据绑定(一)一个简单的例子

控件是用来展示数据的,而不是用来存储数据的

如果把Binding比作数据的桥梁,那么它的两端分别是Binding的源(Source)和目标(Target),数据从哪里来哪里就是源,Binding就是加载中间的桥梁,Binding目标就是数据要到哪儿去,一般情况下,Binding源是逻辑层的对象,Binding目标是UI层的控件对象,这样,数据就会源源不断通过Binding送到UI层,也就完成了数据驱动UI的过程。

如果想让作为Binding源的对象具有自动通知Binding自己属性值已经变化的能力,就需要让类实现INotifyPropertyChanged接口并在属性的set语句中激发PropertyChanged事件。

一个简单的Binding例子,首先定义一个Student类

 

[csharp] view plain copy
 
  1. class Student : INotifyPropertyChanged  
  2. {  
  3.     public event PropertyChangedEventHandler PropertyChanged;  
  4.   
  5.     private string m_Name;  
  6.   
  7.     public string Name  
  8.     {  
  9.         get { return m_Name; }  
  10.         set  
  11.         {  
  12.             m_Name = value;  
  13.             if (PropertyChanged != null)  
  14.             {  
  15.                 PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));  
  16.             }  
  17.         }  
  18.     }  
  19. }  


界面上添加一个TextBox和一个Button

 

 

[html] view plain copy
 
  1. <TextBox x:Name="textBox1"></TextBox>  
  2. <Button Content="Add age" Margin="5" Click="Button_Click"></Button>  

 

 

后台用C#代码将Name属性绑定到TextBox1上

 

[csharp] view plain copy
 
  1. Student stu = new Student();  
  2.   
  3. Binding binding = new Binding();  
  4. binding.Source = stu;  
  5. binding.Path = new PropertyPath("Name");  
  6.   
  7. BindingOperations.SetBinding(textBox1, TextBox.TextProperty, binding);  


这样,当stu对象的Name属性发生变化时,textBox1中的内容就可以自动发生变化了

 

哪个元素是希望通过binding送到UI的呢?这个属性就称为Binding的Path

posted on 2017-07-26 09:05  alex5211314  阅读(112)  评论(0编辑  收藏  举报

导航