编程语言
首页 > 编程语言> > c# – CommandManager.InvalidateRequerySuggested不会触发RequerySuggested

c# – CommandManager.InvalidateRequerySuggested不会触发RequerySuggested

作者:互联网

我正在尝试测试一个使用CommandManager.RequerySuggested的类,并注意到调用CommandManager.InvalidateRequerySuggested不会从我的测试中触发RequerySuggested.这有什么原因以及如何解决这个问题? CommandManager是否需要初始化?

重现问题的代码:

[Test]
public void InvalidateRequerySuggested_TriggersRequerySuggested()
{
    bool triggered = false;
    CommandManager.RequerySuggested += (s, a) => triggered = true;

    CommandManager.InvalidateRequerySuggested();
    Thread.Sleep(1000); // Just to be sure

    Assert.True(triggered); // Never true
}

解决方法:

正如在msdn here上的备注所述,CommandManager.RequerySuggested只保存一个弱事件引用.在你的单元测试中,lambda表达式被垃圾收集.

请尝试以下方法:

bool triggered;
EventHandler handler = (s, e) => triggered = true;
CommandManager.RequerySuggested += handler;
CommandManager.InvalidateRequerySuggested();
GC.KeepAlive(handler);
Assert.IsTrue(triggered);

更新

从进一步的调查来看,我相信我已经找到了问题所在.

CommandManager.InvalidateRequestSuggested()使用当前调度程序异步引发事件.

这是一个解决方案:

bool triggered;
EventHandler handler = (s, e) => triggered = true;
CommandManager.RequerySuggested += handler;
CommandManager.InvalidateRequerySuggested();

// Ensure the invalidate is processed
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Background, new Action(() => { }));

GC.KeepAlive(handler);
Assert.IsTrue(triggered);

标签:c,net,mvvm,wpf,icommand
来源: https://codeday.me/bug/20190625/1283695.html