在我的模型中,我有一些属性,我想在属性发生变化时执行一些额外的代码。我想将新值和属性名称添加到我的数据库中。我还想保留当前警报列表(值等于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并在其他地方为特定属性做一些额外的事情。我打电话叫
RaisePropertyChangedWriteToDbUpdateAlarmList();`
答案 0 :(得分:0)
是的,它非常简单,您只需要使用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);
}
}
}
}