简体   繁体   English

MVVMLight RelayCommand.RaiseCanExecuteChanged 不引发 CanExecuteChanged 事件

[英]MVVMLight RelayCommand.RaiseCanExecuteChanged don't raise the CanExecuteChanged event

I'm developing an application in WPF, with MVVMLight framework.我正在使用 MVVMLight 框架在 WPF 中开发一个应用程序。

I'm trying to make unit tests (i'm novice in that).我正在尝试进行单元测试(我是新手)。 So I try to simulate my view by subscribing to the CanExecuteChanged event on my command and verify that it is correctly called.所以我尝试通过在我的命令上订阅 CanExecuteChanged 事件来模拟我的视图,并验证它是否被正确调用。 But when I do that it is never called, even if I call the RaiseCanExecuteChanged method.但是当我这样做时,它永远不会被调用,即使我调用 RaiseCanExecuteChanged 方法也是如此。

Here is a very simple sample:这是一个非常简单的示例:

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"

What I really can't understand is that it seems to work with my button.我真的无法理解的是它似乎与我的按钮一起工作。 I don't know how but it enables and disables properly.我不知道如何,但它可以正确启用和禁用。

Thank's for your help.谢谢你的帮助。

The RelayCommand 's RaiseCanExecuteChanged method simply calls CommandManager.InvalidateRequerySuggested() which has no effect in the context of a unit test: https://github.com/lbugnion/mvvmlight/blob/b23c4d5bf6df654ad885be26ea053fb0efa04973/V3/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(NET35)/Command/RelayCommandGeneric.cs RelayCommandRaiseCanExecuteChanged方法只是调用CommandManager.InvalidateRequerySuggested() ,它在单元测试的上下文中没有任何效果: https : //github.com/lbugnion/mvvmlight/blob/b23c4d5bf6df654ad885be26ea053fb0efa04973/GVMLightvM.V3 %20(NET35)/Command/RelayCommandGeneric.cs

..because there are no controls that have subscribed to the CommandManager.RequerySuggested event. ..因为没有订阅CommandManager.RequerySuggested事件的控件。

Also, you are generally not really supposed to write unit tests that test the functionality of a third-party framework.此外,您通常不应该编写单元测试来测试第三方框架的功能。 You should probably focus on testing your own custom functionality.您可能应该专注于测试您自己的自定义功能。

But if you want to test the CanExecute method, you should simply call it instead of raising the CanExecuteChanged event:但是如果你想测试CanExecute方法,你应该简单地调用它而不是引发CanExecuteChanged事件:

bool b = testCmd.CanExecute(null);  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM