简体   繁体   English

WPF可以不断执行重新查询

[英]WPF CanExecute Constantly Requerying

I have a property IEnumerable<MyObject> MyObjects in a ViewModel. 我在ViewModel中有一个属性IEnumerable<MyObject> MyObjects I want a certain command in a second view model (that references the first) to be executable when MyObjects is populated with at least one object, but not executable when it's empty. 我希望第二个视图模型(引用第一个)中的某个命令在MyObjects至少填充一个对象时是可执行的,但在它为空时不可执行。

My CanExecute method looks something like this: 我的CanExecute方法看起来像这样:

private bool CanExecute()
{
    return this.viewModel.MyObjects.Any();
}

I have a PropertyChanged event that is raised whenever the underlying value of MyObjects is changed. 每当MyObjects的基础值更改时,都会引发PropertyChanged事件。

The logic works correctly, however the CanExecute() method is constantly being called-- so much that it basically freezes the entire application. 逻辑正常工作,但是CanExecute()方法不断被调用,以至于它基本上冻结了整个应用程序。 At the same time, MyObjects is not changing (nor am I raising the PropertyChanged event for it). 同时,MyObjects并没有改变(我也没有为其引发PropertyChanged事件)。 Any ideas how I can stop the CanExecute from being re-queried constantly? 有什么想法可以阻止CanExecute不断被查询?

I'm assuming your command either inherits RoutedCommand , or it implements CanExecuteChanged like this: 我假设您的命令要么继承RoutedCommand ,要么实现CanExecuteChanged如下所示:

public event EventHandler CanExecuteChanged {
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
}

Which means adding a handler to your command's CanExecuteChanged (which WPF does, to decide when to call your CanExecute ) is equivalent to adding it to CommandManager.RequerySuggested , which is raised very often and as far as I know there is no way to force it to be raised less often. 这意味着将处理程序添加到命令的CanExecuteChanged (WPF会决定何时调用CanExecute )等同于将其添加到CommandManager.RequerySuggested ,据我所知,这是很常见的,没有办法强迫它少养。

There's 2 ways around the problem: 有两种解决方法:

  1. Don't use RequerySuggested at all, just make CanExecuteChanged a standard event and raise it specifically when you want it checked. 根本不使用RequerySuggested ,只需将CanExecuteChanged为标准事件,并在需要检查时专门引发它。

  2. Make sure the CanExecute method is very fast so it doesn't matter how often it runs. 确保CanExecute方法非常快,因此它运行的频率无关紧要。 You could write it as return this.viewModel.HasAnyObjects; 您可以将其编写为return this.viewModel.HasAnyObjects; , where HasAnyObjects is a simple field that is set to true or false when MyObjects changes. ,其中HasAnyObjects是一个简单字段,当MyObjects更改时,该字段设置为true或false。

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

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