即使有模态window,WPF ICommand CanExecute 也会被调用

WPF ICommand CanExecute get called even though there is a modal window

假设我有一个带按钮的用户控件

<UserControl>
<Grid>
    <Button x:Name="button" Content="Show Dialog" DataContext="{Binding m_btnShowDialog}" Style="{StaticResource ButtonVM}" Command="{Binding Cmd}" HorizontalAlignment="Left" Margin="29,56,0,0" VerticalAlignment="Top" Width="75" >
</Grid>
</UserControl>

命令class实现了ICommand接口。
当焦点位于上述对话框时,有时会调用 CanExecute。
这是意料之中的事。

问题是当我单击按钮时,会调用 Execute 方法并弹出一个新的模式对话框。
焦点应该在新对话框上,但由于某些原因,当我与新对话框交互时,CanExecute 仍然被调用。
这种行为正常吗?
我该如何覆盖该行为?
我不希望在显示子模式对话框时调用附加到父对话框控件的命令的 CanExecute 方法。

这是意料之中的。直接引用 WPF 专家 Josh Smith 的话:

WPF will automatically ask all of the commands being used in your UI if they can execute. This happens at various times, such as when input focus shifts to another control, an item is selected in a list, etc. You can also programmatically trigger this to happen by calling the CommandManager’s InvalidateRequerySuggested static method. This all seems magical, dreamy, and almost too good to be true.

您可以获得更详细清晰的解释here

您可以在命令实现中使用 CanExecuteChanged 事件覆盖行为。

class MyCommand : ICommand
{
public bool CanExecute(object parameter)
{
return maybeTrueOrFalse;
}

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

public void Execute(object parameter)
{
// Do something awesome.
}
}