【问题标题】:Prism MVVM ObservesCanExecute - How Do I Nest (Logical AND Over) Simple Observable PropertiesPrism MVVM ObservesCanExecute - 我如何嵌套(逻辑与)简单的可观察属性
【发布时间】:2020-01-18 20:21:50
【问题描述】:

我对 Prism 还很陌生,我无法弄清楚如何利用 ObservesCanExecute(这使我不必手动要求命令重新计算)与多个属性一起使用。使用单一属性,这就像一个魅力!但我想对我所有的三个属性执行“和”。

代码如下:

public ViewModel()
{
    MyCommand = new DelegateCommand(MyCommandHandler).ObservesCanExecute(() => BoolOne).ObservesCanExecute(() => BoolTwo).ObservesCanExecute(() => BoolThree);
}
private bool _boolOne;
public bool BoolOne
{
    get => _boolOne;
    set => SetProperty(ref _boolOne, value);
}
...

我遇到的是,一旦 BoolThree 设置为 true,按钮(附加到此命令)就会启用,而无需检查 BoolOneBoolTwo。我怎样才能让它也像命令谓词一样是return BoolOne && BoolTwo && BoolThree

【问题讨论】:

    标签: c# wpf mvvm prism


    【解决方案1】:

    您需要在此处使用 ObservesProperty 而不是 ObservesCanExecute。 https://prismlibrary.com/docs/commanding.html

    不要尝试链式注册 ObservesCanExecute 方法。 CanExcute 委托只能观察到一个属性。

    使用 ObservesProperty 方法时,您可以链接注册多个属性以进行观察。示例:ObservesProperty(() => IsEnabled).ObservesProperty(() => CanSave)。

    因此您需要将代码更改为:

    MyCommand = new DelegateCommand(MyCommandHandler, MyCanExecuteMethod).ObservesProperty(() => BoolOne).ObservesProperty(() => BoolTwo).ObservesProperty(() => BoolThree);
    
    private void MyCanExecuteMethod()
    {
        return BoolOne && BoolTwo && BoolThree;
    }
    

    这样,当这些属性中的任何一个发生更改时,都会触发 RaiseCanExecuteChanged。

    【讨论】:

    • 那行得通。虽然我想我可以在没有单独定义“CanExecute”的情况下逃脱。谢谢 - 我现在就用这个​​!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多