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

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

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

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

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

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

    class Student : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string m_Name;

        public string Name
        {
            get { return m_Name; }
            set
            {
                m_Name = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
                }
            }
        }
    }

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

        <TextBox x:Name="textBox1"></TextBox>
        <Button Content="Add age" Margin="5" Click="Button_Click"></Button>

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

            Student stu = new Student();

            Binding binding = new Binding();
            binding.Source = stu;
            binding.Path = new PropertyPath("Name");

            BindingOperations.SetBinding(textBox1, TextBox.TextProperty, binding);

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

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



猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/9080412.html
今日推荐