InvokeCommandAction
不知道如何调用 RoutedCommand
。它只调用 ICommand.Execute
这不足以执行它。使用交互行为很少是一个好的解决方案。它只会导致奇怪的设计决策。 WPF 提供了所有必要且强大的功能。用平常的方式处理无聊的事情并没有什么错。事件很好,不违反任何设计模式。为什么要费心添加额外的代码来将事件转换为命令?
您必须实现路由命令处理程序。也不要绑定到静态只读
RoutedCommand
属性。只需将静态 RoutedCommand
值分配给 Button.Command
属性即可。
静态
SystemCommands
类定义了路由命令,例如SystemCommands.MinimizeWindowCommand
以及关联的静态处理程序方法 SystemCommands.MinimizeWindow(Window)
。SystemCommands
还为其每个命令提供了帮助器:CloseWindow()
、MaximizeWindow()
、MinimizeWindow()
、RestoreWindow()
、ShowSystemMenu()
):
MainWindow.xaml
<Window>
<Window.CommandBindings>
<CommandBinding Command="{x:Static SystemCommands.MinimizeWindowCommand}"
Executed="ExecuteMinimizeWindowCommand"
CanExecute="CanExecuteWindowCommands" />
</Window.CommandBindings>
<Button Command="{x:Static SystemCommands.MinimizeWindowCommand}" />
</Window>
MainWindow.xaml.cs
partial class MainWindow : Window
{
private void CanExecuteWindowCommands(object sender, CanExecuteRoutedEventArgs e)
=> e.CanExecute = true;
private void ExecuteMinimizeWindowCommand(object sender, ExecutedRoutedEventArgs e)
=> SystemCommands.MinimizeWindow(this);
}
另一种解决方案是处理
Button.Click
事件并从事件处理程序执行所有必需的操作。