我们在应用程序中使用了caliburn框架。
我的视图模型中有一个属性,该属性应在值更改时为另一个属性调用NotifyOfPropertyChanged
。
我认为我可以做到如下:
public AnalogSensorState State
{
get
{
if (LowerErrorLevelExceeded)
{
return AnalogSensorState.LowerErrorExceeded;
}
if (LowerWarningLevelExceeded)
{
return AnalogSensorState.LowerWarningExceeded;
}
if (UpperErrorLevelExceeded)
{
return AnalogSensorState.UpperErrorExceeded;
}
if (UpperWarningLevelExceeded)
{
return AnalogSensorState.UpperWarningExceeded;
}
return AnalogSensorState.Ok;
}
}
public bool LowerErrorLevelExceeded
{
get => _lowerErrorLevelExceeded;
set
{
Set(ref _lowerErrorLevelExceeded, value, nameof(LowerErrorLevelExceeded));
NotifyOfPropertyChange(() => nameof(State));
}
}
...
执行布尔设置器后,我在NotifyOfPropertyChange
调用中收到无效的强制转换异常。
为什么?
例外:
System.InvalidCastException:'无法转换类型的对象 键入“ System.Linq.Expressions.ConstantExpression” “ System.Linq.Expressions.MemberExpression”。
答案 0 :(得分:2)
您应根据NotifyOfPropertyChange(nameof(State));
中的NotifyOfPropertyChange(() => State);
实现,使用PropertyChangedBase
或Caliburn.Micro
/// <summary>Notifies subscribers of the property change.</summary>
/// <param name="propertyName">Name of the property.</param>
public virtual void NotifyOfPropertyChange([CallerMemberName] string propertyName = null)
{
if (!this.IsNotifying || this.PropertyChanged == null)
return;
this.OnUIThread((Action) (() => this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName))));
}
public void NotifyOfPropertyChange<TProperty>(Expression<Func<TProperty>> property)
{
this.NotifyOfPropertyChange(property.GetMemberInfo().Name);
}