MVVMLight RelayCommand.RaiseCanExecuteChanged 不引发 CanExecuteChanged 事件
MVVMLight RelayCommand.RaiseCanExecuteChanged don't raise the CanExecuteChanged event
我正在使用 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"
我真正无法理解的是它似乎适用于我的按钮。我不知道如何正确启用和禁用。
感谢您的帮助。
RelayCommand
的 RaiseCanExecuteChanged
方法只是调用 CommandManager.InvalidateRequerySuggested()
,这在单元测试的上下文中没有任何效果:https://github.com/lbugnion/mvvmlight/blob/b23c4d5bf6df654ad885be26ea053fb0efa04973/V3/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(NET35)/Command/RelayCommandGeneric.cs
..因为没有控件订阅了CommandManager.RequerySuggested
事件。
此外,您通常不应该真正编写单元测试来测试 third-party 框架的功能。您可能应该专注于测试您自己的自定义功能。
但是如果你想测试 CanExecute
方法,你应该简单地调用它而不是引发 CanExecuteChanged
事件:
bool b = testCmd.CanExecute(null);
我正在使用 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"
我真正无法理解的是它似乎适用于我的按钮。我不知道如何正确启用和禁用。
感谢您的帮助。
RelayCommand
的 RaiseCanExecuteChanged
方法只是调用 CommandManager.InvalidateRequerySuggested()
,这在单元测试的上下文中没有任何效果:https://github.com/lbugnion/mvvmlight/blob/b23c4d5bf6df654ad885be26ea053fb0efa04973/V3/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(NET35)/Command/RelayCommandGeneric.cs
..因为没有控件订阅了CommandManager.RequerySuggested
事件。
此外,您通常不应该真正编写单元测试来测试 third-party 框架的功能。您可能应该专注于测试您自己的自定义功能。
但是如果你想测试 CanExecute
方法,你应该简单地调用它而不是引发 CanExecuteChanged
事件:
bool b = testCmd.CanExecute(null);