wpf 属性变更通知接口 INotifyPropertyChanged

在wpf中将控件绑定到对象的属性时, 当对象的属性发生改变时必须通知控件作出相应的改变, 所以此对象需要实现 INotifyPropertyChanged 接口

例1: (注意:从 .Net 4.5 才开始支持此特性)

    //实现属性变更通知接口 INotifyPropertyChanged
    public class TestA : INotifyPropertyChanged
    {
        public long ID { get; set; }

        private string name;
        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                if (value != this.name)
                {
                    this.name = value;
                    //调用属性变更通知方法
                    NotifyPropertyChanged();
                }
            }
        }

        // INotifyPropertyChanged 接口成员
        public event PropertyChangedEventHandler PropertyChanged;
        //此方法在每个属性的set中调用
        //在可选参数propertyName上应用CallerMemberName特性
        //调用此方法时,调用方的信息将替换为可选参数的参数,即在set中调用此方法,propertyName="当前属性的名称"
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }

 例2:(.net 4.0)

    //实现属性变更通知接口 INotifyPropertyChanged
    public class TestA : INotifyPropertyChanged
    {
        public long ID { get; set; }

        private string name;
        public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                if (value != this.name)
                {
                    this.name = value;
                    //调用属性变更通知方法,参数为"属性名称"
                    NotifyPropertyChanged("Name");
                }
            }
        }

        // INotifyPropertyChanged 接口成员
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

    }

 

转载于:https://www.cnblogs.com/gmcn/p/5882026.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值