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

标签 c# wpf mvvm prism

我想在我的 View 模型中观察多个属性,以检查CanExecute方法。

问题:

如何注册更多属性(property)?

示例:

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;

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

最佳答案

像您正在做的那样为另一个属性调用ObservesProperty方法应该可以。但是您需要在源属性的设置程序中引发PropertyChanged事件,以引发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()
    {

    }
}

关于c# - 如何使用Delegatecommand.ObservesProperty观察多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45049548/

相关文章:

c# - 不确定进度条

c# - 如何从基类中获取自定义属性?

c# - Internet Explorer 缓存从数据库返回的数据

c# - 在 WPF 中将 Canvas 绑定(bind)到 Canvas

c# - 带有 Interop 库的临时 Excel 文件

wpf - ViewModel 可以与 MVVM 模式中的 View 对话吗?

mvvm - knockout View 模型和requirejs

c# - 绑定(bind) TabItem 可见性

WPF/XAML - 选中单选按钮时设置 ValidatesOnDataErrors = false/true 的 DataTriggers

c# - 设置 textBox.Text 不会更新绑定(bind)的双向属性?