【问题标题】:MVVMLight RelayCommand.RaiseCanExecuteChanged don't raise the CanExecuteChanged eventMVVMLight RelayCommand.RaiseCanExecuteChanged 不引发 CanExecuteChanged 事件
【发布时间】:2018-03-01 16:24:11
【问题描述】:

我正在使用 MVVMLight 框架在 WPF 中开发应用程序。

我正在尝试进行单元测试(我是新手)。所以我尝试通过订阅我的命令上的 CanExecuteChanged 事件来模拟我的视图,并验证它是否被正确调用。但是当我这样做时,它永远不会被调用,即使我调用了 RaiseCanExecuteChanged 方法。

这是一个非常简单的示例:

bool testCanExec = false;
var testCmd = new RelayCommand(
                     execute:    () => { System.Diagnostics.Debug.WriteLine($"Execute call"); },
                     canExecute: () => { System.Diagnostics.Debug.WriteLine($"CanExecute call"); return testCanExec; }
                );
testCmd.CanExecuteChanged += ((sender, args) => { System.Diagnostics.Debug.WriteLine($"CanExecuteChanged call"); });
testCanExec = true;
testCmd.RaiseCanExecuteChanged(); // <= nothing in output
testCmd.Execute(null);            // <= output: "CanExecute call", "Execute call"

我真正无法理解的是,它似乎可以与我的按钮一起使用。我不知道如何,但它可以正确启用和禁用。

感谢您的帮助。

【问题讨论】:

    标签: c# wpf mvvm-light relaycommand


    【解决方案1】:

    RelayCommandRaiseCanExecuteChanged 方法只是调用CommandManager.InvalidateRequerySuggested(),这在单元测试的上下文中没有任何作用:https://github.com/lbugnion/mvvmlight/blob/b23c4d5bf6df654ad885be26ea053fb0efa04973/V3/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(NET35)/Command/RelayCommandGeneric.cs

    ..因为没有控件订阅了CommandManager.RequerySuggested 事件。

    此外,您通常不应该编写单元测试来测试第三方框架的功能。您可能应该专注于测试您自己的自定义功能。

    但如果你想测试CanExecute 方法,你应该简单地调用它而不是引发CanExecuteChanged 事件:

    bool b = testCmd.CanExecute(null);  
    

    【讨论】:

    • 谢谢你的解释。事实上我不想测试 MVVMLight 框架,我只是想确保 CanExecuteChanged 事件正确引发,因为 CanExecute 方法使用了许多其他属性,所以我必须每次更改这些字段之一时调用 RaiseCanExecuteChanged 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多