WPF学习笔记

《深入浅出WPF》学习笔记

第6章 深入浅出话Binding

6.2 Binding基础

  如果把Binding比作数据的桥梁,那么它的两端分别是Binding的源(Source)和目标(Target)。一般源是逻辑层对象,目标是UI层控件对象.

  我们可以控制源与目标是双向通行还是单向,还可以控制对数据放行的时机,还可以设置“关卡”转换数据类型或校验数据的正确性。

class Student
{
    public string Name {get;set;}
    public string Age {get;set;}
}

  Path:如上所示,一个对象有多个属性,UI上关心哪个属性值的变化呢?这个属性就称为Binding的路径(Path)

  PropertyChanged:让属性具备通知Binding值已变化的能力。作为数据源的类实现INotifyPropertyChanged接口。

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

  Binding的过程:

Student stu = new Student();
Binding binding = new Binding(); binding.Source = stu; binding.Path = new PropertyPath("Name"); BindingOperations.SetBinding(this.textBoxName,TextBox.TextProperty,binding);

  主要是 源、路径、设置绑定

  

  实际工作中,实施Binding的代码可能与上面不太一样,因为TextBox这类UI元素的基类FramewordElement对BindingOperation.SetBinding(...)方法进行了封装,封装的结果也叫SetBinding,只是参数列表发送了变化  

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

  借助Binding类的构造器及C#3.0的对象初始化器语法简化上述代码

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

6.3 Binding的源与路径

  源:只要是一个对象,并行通过属性(Property)公开自己的数据,它就能作为Binding的源

多数情况下,我们会选择ListView控件来显示一个DataTable

猜你喜欢

转载自www.cnblogs.com/code1992/p/10250440.html
今日推荐