wpf - MVVM 灯。当属性的值真正改变时执行方法的正确方法
问题描述
此代码允许在设置属性时执行该方法。它执行的次数与设置属性的次数一样多。我想知道只有在属性值真正改变时才执行该方法的变体。
public const string MyPropertyPropertyName = "MyProperty";
private bool _myProperty = false;
public bool MyProperty
{
get
{
return _myProperty;
}
set
{
Set(MyPropertyPropertyName, ref _myProperty, value);
DoSomething();
}
}
private void DoSomething()
{
// DO YOUR WORK
}
解决方案
该Set
方法应返回一个bool
值,该值指示该属性是否被实际设置:
set
{
if (Set(MyPropertyPropertyName, ref _myProperty, value))
DoSomething();
}
如果它没有返回值,您应该修改它或使用您自己的自定义Set
方法:
protected bool Set<T>(string propertyName, ref T storage, T value)
{
if (Equals(storage, value))
return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
推荐阅读
- common-lisp - Common Lisp 中是否有任何线程安全的哈希表实现?
- python - 我的代码没有在 IntelliJ python 中返回。为什么不回来?我知道有一个基本原因
- android - ios中的标签栏位于屏幕顶部
- python - Python从复杂字典创建子字典
- django - 在Django中选择文件后预览照片
- git - 修改先前提交的实际代码文件(c#、java 等)(使用 git)?
- ruby - cancancan的多级授权
- javascript - 棋盘Java脚本建议需要
- serialization - 使用协议缓冲区序列化/反序列化对象
- c# - 如何通过查询旧列表 c# 中的最新文件来填充新列表?