如何使用 Delegatecommand.ObservesProperty 观察多个属性

How to observe multiple properties with Delegatecommand.ObservesProperty

我想观察我的视图模型中的多个属性以检查 CanExecute 方法。

问题:

如何登记更多房源?

示例:

class MyViewModel
        {
            public int myproperty1 { get; set; }
            public int myproperty2 { get; set; }

            public DelegateCommand MyCommand { get; set; }

            public MyViewModel()
            {
                MyCommand = new DelegateCommand(MyCommandMethod,CanExecuteMyCommandMethod);
                MyCommand.ObservesProperty((() => myproperty1));
                // line below doesnt work Exeception "Value is already observed". How to register more properties to observe?
                MyCommand.ObservesProperty((() => myproperty2));

            }

            private bool CanExecuteMyCommandMethod()
            {
                throw new NotImplementedException();
            }

            private void MyCommandMethod()
            {
                throw new NotImplementedException();
            }
        }

更新:

PropertChanged 事件由 Propertchanged.Fody INPC 完成。

ObservesProperty 用于 RaiseCanExecuteChanged。 第二个 属性 观察注册引发异常“值已被观察到”。

附加问题: ObservesProperty((() => 我的属性;

允许多个还是单个 属性? 如果其他人确认可以多次注册?

像您一样为另一个 属性 调用 ObservesProperty 方法应该可行。但是您需要在要引发的 CanExecuteChanged 事件的源属性的设置器中引发 PropertyChanged 事件。

请参考下面的示例代码

public class MyViewModel : BindableBase
{
    private int _myproperty1;
    public int myproperty1
    {
        get { return _myproperty1; }
        set { _myproperty1 = value; RaisePropertyChanged(); }
    }

    private int _myproperty2;
    public int myproperty2
    {
        get { return _myproperty2; }
        set { _myproperty2 = value; RaisePropertyChanged(); }
    }

    public DelegateCommand MyCommand { get; set; }

    public MyViewModel()
    {
        MyCommand = new DelegateCommand(MyCommandMethod, CanExecuteMyCommandMethod);
        MyCommand.ObservesProperty((() => myproperty1));
        MyCommand.ObservesProperty((() => myproperty2));
    }

    private bool CanExecuteMyCommandMethod()
    {
        return true;
    }

    private void MyCommandMethod()
    {

    }
}