wpf RelayCommand CanExecute 行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15065885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:42:41  来源:igfitidea点击:

RelayCommand CanExecute behavior

c#wpfmvvmmvvm-light

提问by Night Walker

I have following command:

我有以下命令:

<Button x:Name="bOpenConnection" Content="Start Production"
        Grid.Row="0" Grid.Column="0"
        Height="30" Width="120" Margin="10"
        HorizontalAlignment="Left" VerticalAlignment="Top" 
        Command="{Binding Path=StartProductionCommand}"/>

StartProductionCommand = new RelayCommand(OpenConnection, CanStartProduction);

private bool CanStartProduction()
{
   return LogContent != null && !_simulationObject.Connected;
}

CanStartProductionis checked only when I re-size the UI and not updated on the fly. Any idea why it's not updated every time they change the values ?

CanStartProduction仅在我重新调整 UI 大小时才检查,而不是即时更新。知道为什么每次更改值时都不更新吗?

回答by Thomas Levesque

The CommandManagerhas no way of knowing that the command depends on LogContentand _simulationObject.Connected, so it can't reevaluate CanExecuteautomatically when these properties change.

CommandManager没有知道该命令取决于方式LogContent_simulationObject.Connected,因此它不能重新评估CanExecute时,自动将这些特性的变化。

You can explicitly request a reevaluation by calling CommandManager.InvalidateRequerySuggested. Note that it will reevaluate CanExecutefor allcommands; if you want to refresh only one, you need to raise the CanExecuteChangedevent on the command itself by calling StartProductionCommand.RaiseCanExecuteChanged.

您可以通过调用显式请求重新评估CommandManager.InvalidateRequerySuggested。请注意,它会重新评估CanExecute所有的命令; 如果只想刷新一个,则需要CanExecuteChanged通过调用StartProductionCommand.RaiseCanExecuteChanged.

回答by Boas Enkler

You can call RaiseCanExecuteChanged in the For example PropertyChanged Eventhandler.

您可以在例如 PropertyChanged 事件处理程序中调用 RaiseCanExecuteChanged。

Command states are not refreshed very often.

命令状态不会经常刷新。

Sometime ago I read a good article about it. I will post it later on.

前段时间我读了一篇关于它的好文章。稍后我会发布它。

see also http://joshsmithonwpf.wordpress.com/2008/06/17/allowing-commandmanager-to-query-your-icommand-objects/

另见http://joshsmithonwpf.wordpress.com/2008/06/17/allowing-commandmanager-to-query-your-icommand-objects/

see also Refresh WPF Command

另请参阅刷新 WPF 命令