重写RaisePropertyChanged以执行其他代码
本文关键字:其他 代码 执行 RaisePropertyChanged 重写 | 更新日期: 2023-09-27 18:27:46
在我的模型中,我有一些属性,当属性更改时,我想执行一些额外的代码。我想将新值和属性名称添加到我的数据库中。我还想保留一个当前警报的列表(值等于true)。
public Boolean ActionAlarmLowLow
{
get
{
return _ActionAlarmLowLow;
}
set
{
if (value != this._ActionAlarmLowLow)
{
Boolean oldValue = _ActionAlarmLowLow;
_ActionAlarmLowLow = value;
RaisePropertyChanged("ActionAlarmLowLow", oldValue, value, true);
}
}
}
我怎样才能正确地做到这一点?我想知道我是否应该向属性添加两行代码:
DB.Log.addLogItem("ActionAlarmLowLow", value);
AlarmList.UpdateItem("ActionAlarmLowLow", value);
或者,如果我可以以某种方式扩展/覆盖RaisePropertyChanged,并在其他地方为特定属性做一些额外的事情。I.e叫
RaisePropertyChangedWriteToDbUpdateAlarmList();`
是的,它非常简单,您只需要创建一个具有INotifyPropertyChanged的基类,并调用内部所需的任何内容。
public abstract class NotifyPropertyChangedBase: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged<T>(Expression<Func<T>> expression)
{
var memberExpression = (MemberExpression) expression.Body;
var propertyName = memberExpression.Member.Name;
var handler = PropertyChanged;
if (handler != null)
{
// Do your common actions here, before property change notification is fired
handler(this, new PropertyChangedEventArgs(propertyName));
// Do your common actions here, after property change notification is fired
}
}
}
public class MyClass : NotifyPropertyChangedBase
{
public Boolean ActionAlarmLowLow
{
get
{
return _ActionAlarmLowLow;
}
set
{
if (value != this._ActionAlarmLowLow)
{
_ActionAlarmLowLow = value;
OnPropertyChanged(() => this.ActionAlarmLowLow);
}
}
}
}