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

时间:2017-07-12 06:00:03

标签: c# wpf mvvm prism

我想在viewmodel中观察多个属性来检查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((()=> myproperty;

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

1 个答案:

答案 0 :(得分:0)

ObservesProperty方法调用为您正在执行的其他属性应该可行。但是,您需要在要添加的PropertyChanged事件的源属性的setter中引发CanExecuteChanged事件。

请参阅以下示例代码。

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()
    {

    }
}