Caliburn NotifyOfPropertyChanged:System.InvalidCastException

时间:2019-09-04 07:52:44

标签: wpf mvvm caliburn.micro

我们在应用程序中使用了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”。

1 个答案:

答案 0 :(得分:2)

您应根据NotifyOfPropertyChange(nameof(State));中的NotifyOfPropertyChange(() => State);实现,使用PropertyChangedBaseCaliburn.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);
    }
相关问题