Binding自动侦听

WPF的强大之一就是数据绑定,Binding是数据桥梁,它的两端是分别是源(Source)和目标(Target),一个简单的类的属性值发生变化,会自动反映在UI界面上,这个属性就是Binding的Path路径,那么如何自动反映在UI界面上的呢?其实就是数据源要实现INotifyPropertyChanged接口,其属性的set语句中实现一个PropertyChanged事件,当为Binding设置数据源后,Binding就会自动侦听来自这个接口的PropertyChanged事件

看看下面例子,类Stuent实现接口,Name属性set中添加事件,这样此Name变化会反映到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(this, new PropertyChangedEventArgs("Name"));
            }
        }
    }

用代码在后台绑定到UI界面上的textBox文件框上,如下

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

 

或在控件上直接写绑定:

    

   <TextBox x:Name="textBox" Text="{Binding Name}" />

 

在初始化窗口中添加数据源:

 public MainWindow()
        {
            InitializeComponent();
            student = new Student()
            {
                Name = "张三"
            };

            this.textBox.DataContext = student;
         }
        Student student;

 

在项目中,可以PropertyChanged事件可以提取成基类,使用代码简洁一些

 class NotifyObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

在属性中就可以这样写:

class Student : NotifyObject
    {

        private string name;

        public string Name
        {
            get { return name; }
            set { name = value;
                RaisePropertyChanged("Name");
            }
        }
    }

 

posted @ 2015-09-13 08:53  lunawzh  阅读(235)  评论(0编辑  收藏  举报