Binding的简单使用

     Binding可以看作是数据的桥梁,两端分别为Source和Target,一般情况,Source是逻辑层的对象,Target是UI层的控件对象,可以将数据从逻辑层送往UI层展现


简单的例子:

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"));
            }
            
            }
        }
这个学生类是Source,暴露出来的属性Name就是 Binding的Path,此处实现的接口(INotifyPropertyChanged)可以让属性具备通知Binding值变化的能力.

<StackPanel>
<TextBox x:Name="textBoxName" BorderBrush="Black" Margin="5" Height="30"/>
<Button Content="Add Age" Margin="5" Click="Button_Click"/>
</StackPanel>

这是UI放了一个TextBox和Button


student = new Student();
Binding binding = new Binding();
binding.Source = student;//Binding 的Source
binding.Path = new PropertyPath("Name");//Binding指定访问路径,就是Student类的Name属性

BindingOperations.SetBinding(this.textBoxName, TextBox.TextProperty, binding);//1.Binding 的Target,2.数据送达的Target的属性 (依赖属性).3.哪个Binding


 

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

点击按钮改变Source的Name属性。

以上这个小栗子是关于,最简单的对象和Binding的使用

posted @ 2019-08-02 23:58  拎着红杯子的黄鸭子  Views(500)  Comments(0Edit  收藏  举报