zoukankan      html  css  js  c++  java
  • InotifyPropertyChanged接口实现简单数据绑定

    UI跟踪对象变化的一种常用方式就是在对象属性发生变化时触发相关的事件。为此对象就必须实现InotifyPropertyChanged接口。

    在Msdn上是这样描述的:向客户端发出某一属性值已更改的通知。

    下面看一个例子:

    public class Person: InotifyPropertyChanged

    {

    public eventPropertyChangedEventHandler propertyChanged;

    protected voidNotify(string propName)

    {

    if(this.PropertyChanged!=null)

    {

           propertyChanged(this,newpropertyChangedEventArgs(propName));

    }


    }

    string name;

    public stringName

    {

    get{return this.name;}

    set

    {

           if(this.name==value){return;}

           this.name=value;

           Notify(“Name”);

    }
    }

           intage;

           publicint Age
           {

    get{return this.age;}

    set

    {

           if(this.age==value){return;}

           this.age=value;

           Notify(“Age”);

    }

           }

    }

    当Person对象属性发生变化时,Person类就会触发PropertyChanged事件,利用此事件可以让textbox的内容和Person类的属性值保持同步。

    具体实现如下:

    Class Window1:Window

    {

    Person person =new Person(“Tom”,11);

    Person.PropertyChanged+=person_PropertyChanged;
    }

    Void person_PropertyChanged(objectsender,PropertyChangedEventArgs e)

    {

    switch(e.PropertyName)
    {

    case “Name”:

    this.nameTextBox.Text=person.Name;

    bresk;

    case “Age”:

    this.ageTextBox.Text=person.Age;

    break;
    }

    }

    这里注册了person类属性的变更事件PropertyChanged,从而保证了文本框和对象属性的同步。需要注意的是,用户修改控件TextBox的内容时person对象的属性不会发生变化,需要使用TextChanged事件对person类属性进行变更。

  • 相关阅读:
    python-ConfigParser模块【读写配置文件】
    MinGW安装和使用
    mybatis批量操作
    SSM框架的简单搭建
    idea录制宏
    数据导出,导入
    JS中调用android和ios系统手机打开相机并可选择相册功能
    get请求中url传参中文乱码问题
    hibernate criteria中Restrictions的用法
    hibernate报错
  • 原文地址:https://www.cnblogs.com/fornet/p/2976189.html
Copyright © 2011-2022 走看看