WPF系列之三:实现类型安全的INotifyPropertyChanged接口,可以不用“Magic string” 么?
通常实现INotifyPropertyChanged接口很简单,为你的类只实现一个PropertyChanged 的Event就可以了。
例如实现一个简单的ViewModel1类:
public class ViewModel1 : INotifyPropertyChanged
{
private string _data;
public string Data
{ get { return _data; }
set
{
if (_data == value)
return;
_data = value;
// Type un-safe PropertyChanged raise
PropertyChanged(this, new PropertyChangedEventArgs("Data"));
}
}
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged = null;
#endregion
}
ViewModel1
上面是一个标准的实现一个可绑定的属性的方式,问题是其中使用了一个“Data”的字符串来表明发生变化的属性名。问题在于如果有人改变了属性的名字而忘记改变这里的字符串的话
,即使编译不会产生问题,但binding也会失败掉。最好的方法当然是当有人改变属性的名字时,编译器可以告诉我们这个地方也需要相应改变。
例如实现下面这样:
private string _data;
public string Data
{ get { return _data; }
set
{
PropertyChanged.ChangeAndNotify(ref _data, value, () => Data);
}
}
类型安全的通知更新
让我们利用扩展方法来扩展PropertyChangedEventHandler实现这个目标:
public static class PropertyChangedEventHandlerExtentions
{
public static bool ChangeAndNotify<T>(this PropertyChangedEventHandler handler, ref T field, T value, Expression<Func<T>> memberExpression)
{
if (memberExpression == null)
{
throw new ArgumentNullException("memberExpression");
}
// Retreive lambda body
var body = memberExpression.Body as MemberExpression;
if (body == null)
{
throw new ArgumentException("Lambda must return a property.");
}
if (EqualityComparer<T>.Default.Equals(field, value))
{
//值没有发生变化,不通知更新
return false;
}
// Extract the right part (after "=>")
var vmExpression = body.Expression as ConstantExpression;
if (vmExpression != null)
{
// Create a reference to the calling object to pass it as the sender
LambdaExpression lambda = Expression.Lambda(vmExpression);
Delegate vmFunc = lambda.Compile();
object sender = vmFunc.DynamicInvoke(); if (handler != null)
{
//body.Member.Name,Extract the name of the property to raise a change on
handler(sender, new PropertyChangedEventArgs(body.Member.Name));
}
}
field = value;
return true;
}
}
PropertyChangedEventHandlerExtentions
方法的核心思想就是1.利用扩展方法来扩展delegate:PropertyChangedEventHandler,2.用引用传值把原来的值传入扩展方法用来做比较,3.用lambda expression表达式树来传递待更新的属性名称来达到类型安全的目的,并且传递了调用这个lambda的对象实例(sender)。
如果上面的方法比较难理解,我觉得下面的方法也是可以接受的:
1.依然传递Magic string,但是可以简化值比较的代码:
public class Data : INotifyPropertyChanged
{
// boiler-plate
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value, string propertyName)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
} // props
private string name;
public string Name
{
get { return name; }
set { SetField(ref name, value, "Name"); }
}
}
2.不用传递Magic string,也不用ExtentionMethod,只利用lambda expression来取得属性名:
public class Data2 : INotifyPropertyChanged
{
// boiler-plate
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged<T>(Expression<Func<T>> selectorExpression)
{
if (selectorExpression == null)
throw new ArgumentNullException("selectorExpression");
MemberExpression body = selectorExpression.Body as MemberExpression;
if (body == null)
throw new ArgumentException("The body must be a member expression");
OnPropertyChanged(body.Member.Name);
}
protected bool SetField<T>(ref T field, T value, Expression<Func<T>> selectorExpression)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(selectorExpression);
return true;
}
// props
private string name;
public string Name
{
get { return name; }
set { SetField(ref name, value, () => Name); }
}
}
完毕。
参考文章:
http://www.wpftutorial.net/INotifyPropertyChanged.html
http://blog.decarufel.net/2009/07/how-to-use-inotifypropertychanged-type_22.html
作者:Andy Zeng
欢迎任何形式的转载,但请务必注明出处。
http://www.cnblogs.com/andyzeng/p/3710421.html
WPF系列之三:实现类型安全的INotifyPropertyChanged接口,可以不用“Magic string” 么?的更多相关文章
- [译]WPF MVVM 架构 Step By Step(5)(添加actions和INotifyPropertyChanged接口)
应用不只是包含textboxs和labels,还包含actions,如按钮和鼠标事件等.接下来我们加上一些像按钮这样的UI元素来看MVVM类怎么演变的.与之前的UI相比,这次我们加上一个"C ...
- 转载:WPF MVVM之INotifyPropertyChanged接口的几种实现方式
原文地址:http://www.cnblogs.com/xiwang/ 序言 借助WPF/Sliverlight强大的数据绑定功能,可以比实现比MFC,WinForm更加优雅轻松的数据绑定.但是在使用 ...
- WPF编游戏系列 之三 物品清单
原文:WPF编游戏系列 之三 物品清单 本篇将介绍如何通过C#自动生成游戏界面,主要演示点击"My Shop"后如何显示所有物品清单.其中数据源来自于Access 2 ...
- WPF MVVM之INotifyPropertyChanged接口的几种实现方式(转)
原地址:https://www.cnblogs.com/xiwang/archive/2012/11/25/2787358.html 序言 借助WPF/Sliverlight强大的数据绑定功能,可以比 ...
- WPF学习总结1:INotifyPropertyChanged接口的作用
在代码中经常见到这个接口,它里面有什么?它的作用是什么?它和依赖属性有什么关系? 下面就来总结回答这三个问题. 1.这个INotifyPropertyChanged接口里就一个PropertyChan ...
- WPF学习笔记:(二)数据绑定模式与INotifyPropertyChanged接口
数据绑定模式共有四种:OneTime.OneWay.OneWayToSource和TwoWay,默认是TwoWay.一般来说,完成数据绑定要有三个要点:目标属性是依赖属性.绑定设置和实现了INotif ...
- (C#)WPF:关于INotifyPropertyChanged接口的介绍
注意:INotifyPropertyChanged接口位于System.CompenentModel名称空间中,想使用INotifyPropertyChanged接口时,头文件需添加“using Sy ...
- WPF 之 INotifyPropertyChanged 接口的使用 (一)
一.INotifyPropertyChanged 的基本概念 INotifyPropertyChanged 的作用:通知客户端属性值已经更改.详细信息见:INotifyPropertyChange ...
- 如何优雅的实现INotifyPropertyChanged接口
INotifyPropertyChanged接口在WPF或WinFrom程序中使用还是经常用到,常用于通知界面属性变更.标准写法如下: class NotifyObject : INotifyProp ...
随机推荐
- Codeforces Round #553 (Div. 2) C
C. Problem for Nazar time limit per test 1 second memory limit per test 256 megabytes input standard ...
- Seven super tips for successful selling on Amazon
Check for orders daily: To ship quickly you need to find out about orders promptly. We will e-mail y ...
- python基础知识-7-内存、深浅、文件操作
python其他知识目录 1.一些对内存深入理解的案例 以下列举列表,列表/字典/集合这些可变类型都是一样的原理 变量是个地址,指向存储数据的内存空间的地址,它的实质就相当于c语言里的指针.变量和数据 ...
- react-native debug js remotely跨域问题
react-native debug js remotely跨域问题 我们在安卓真机上调试react-native时,启用debug js remotely的时候,会出现跨域问题.这个时候我们只需要一 ...
- 吴恩达机器学习笔记——正规方程(Normal Equation)
问题描述:m examples : (x(1),y(1)), (x(2),y(2)),..., (x(m),y(m)) and n features; 计算方法:θ = (XTX)-1XTy; 计算过 ...
- Java课程实验报告 实验四 Java网络编程及安全
北京电子科技学院(BESTI) 实 验 报 告 课程:Java程序设计 班级:1352 姓名:吕松鸿 学号:20135229 成绩: ...
- mysql 查询数据库或某张表有多大(字节)
转载:https://www.cnblogs.com/diandiandidi/p/5582309.html 1.要查询表所占的容量,就是把表的数据和索引加起来就可以了 select sum(DATA ...
- 大学网站UI设计分析(以学校领导/历届领导为例)
第一次的冲刺阶段让我过了一把PM的瘾,第一阶段的冲刺完成以后第一感觉就是PM不好当,在大学里做个课程设计当个PM相对而言还是比较容易的,但是我明白,当我们走向工作岗位以后,面临的情况会比学校的情况的复 ...
- xheditor在线编辑器在.netMVC4中的使用
在线编辑器xheditor,测试感觉不错,特把使用方法记录如下 : 先看看基本使用方法,然后用实例来操作 1.xheditor 地址 http://xheditor.com/ 2.下载最新编辑器源码 ...
- BZOJ4916 神犇和蒟蒻(欧拉函数+杜教筛)
第一问是来搞笑的.由欧拉函数的计算公式容易发现φ(i2)=iφ(i).那么可以发现φ(n2)*id(n)(此处为卷积)=Σd*φ(d)*(n/d)=nΣφ(d)=n2 .这样就有了杜教筛所要求的容易算 ...