Binding基础

xiaoxiao2021-02-28  100

Binding基础

一般情况,Binding Source是逻辑层的对象,Binding Target是UI层的控件对象。

举例如下:

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

UI上的元素关心的是哪个属性的值变化,这个属性就称为Binding的Path,但光有属性还不行-Binding是一种自动机制,需要在属性的set语句中激发一个PropertyChanged事件。这个事件不需要我们自己声明,我们要做的是让数据源的类实现System.ComponentModel名称空间的*INotifyPropertyChanged *接口。

接下来,我们进入重要的一步-使用Binding把数据源和UI元素连接起来。

//准备数据源 Student stu = new Student(); //准备Binding Binding binding = new Binding(); binding.Source = stu; binding.Path=new PropertyPath("Name"); //使用Binding连接数据源与Binding目标 BindingOperations.SetBinding(this.textBoxName, TextBox.TextProperty, binding); 第一个参数用于指定Binding的目标,本例中是this.textBoxName与数据源的Path原理类似,第二个参数用于为Binding指明把数据送到目标的哪个属性。这里用的是类的一个静态只读(static readonly)的DependencyProperty类型成员变量。这就是与Binding息息相关的依赖属性第三个参数就是指定使用哪个Binding实例将数据源与目标关联起来
转载请注明原文地址: https://www.6miu.com/read-19814.html

最新回复(0)