DataBinding快速入门(1)

       Binding就好像桥梁,通过这座桥连通数据源和目标。数据源通常是逻辑层,目标则通常是UI层,因此数据驱动UI,数据占有核心地位。并且在这所桥梁上你就是总都督,你可以控制桥梁是单向还是双向通行,以及数据源放行通过的时间,或者建立关卡校验数据源等等。

       数据源类如下:

public class Student : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return name; }
set
{
name = value;
if ( PropertyChanged != null)
{
this. PropertyChanged. Invoke( this, new PropertyChangedEventArgs( "Name"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}

       作为数据源的类必须实现System.ComponentModel命名空间中的INotifyPropertyChanged接口。为Binding设置好数据源后,就会自动监听来自这个接口PropertyChanged事件。收到消息告诉它是Name的属性值发生变化,最后通知Binding目标端的UI对应元素显示新值。

< Window x:Class= "Demo01.MainWindow"
xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x= "http://schemas.microsoft.com/winfx/2006/xaml"
Title= "Simple Binding" Height= "350" Width= "525" >
< StackPanel >
< TextBox x:Name= "textBoxName" BorderBrush= "Black" Margin= "5" />
< Button Content= "Add Age" Margin= "5" Click= "Button_Click" />
</ StackPanel >
</ Window >
      运行效果如下:
 

      搭桥连接数据源和UI目标端代码如下:

public partial class MainWindow : Window
{
Student stu;
public MainWindow()
{
InitializeComponent();

// 准备数据源
stu = new Student();

// 准备Binding
Binding bind = new Binding();
bind. Source = stu; // 为实例准备数据源
bind. Path = new PropertyPath( "Name");

// 使用Binding连接数据源与Binding目标
BindingOperations. SetBinding( this. textBoxName, TextBox. TextProperty, bind);

}

private void Button_Click( object sender, RoutedEventArgs e)
{
stu. Name += "Name";
}
}

       Student类实例stu就是Binding一端的源数据。主要需要Binding对象来建立桥梁的搭建工程。首先给Source和Path属性赋值,为Binding实例指定数据源和访问路径。BindingOperations类SetBinding函数完成搭建任务,第一个参数是指定目标端;第二个是源数据送达目标端的哪个属性,这个属性是类的静态只读属性(static readonly)的DependencyProperty类型成员变量;第三个参数则是Binding对象

      点击按钮的现象如下图:


   实际开发中,不会运用上面繁琐的方式,因为TextBox这类UI控件的基类是FrameworkElement对BindingOperations.SetBinding(…)进行封装,封装的接口也叫SetBinding。代码如下:

public BindingExpressionBase SetBinding( DependencyProperty dp, BindingBase binding)
{
return BindingOperations. SetBinding( this, dp, binding);
}

      第二个参数可以借助Binding类的构造器及对象初始化器来简化代码。代码如下:

public MainWindow()
{
InitializeComponent();

this. textBoxName. SetBinding( TextBox. TextProperty, new Binding( "Name")
{ Source = stu = new Student() });
}

     下图是Binding模型:


      本文只是简要介绍DataBinding的基本使用,更详细的细节会再后面进行总结,谢谢。

发布了34 篇原创文章 · 获赞 12 · 访问量 2538

猜你喜欢

转载自blog.csdn.net/u013946061/article/details/80731726