前面,大概瞭解使用WPF中已定義的命令的各種方法,現在實現自己的命令。
最簡單方法是使用包含它們的靜態類。
WPF由於一些奇怪的原因,沒有實現退出/離開命令,可以自定義命令示例實現一個。
<Window x:Class="命令.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:self="clr-namespace:命令"
Title="MainWindow" Height="200" Width="250">
<Window.CommandBindings>
<CommandBinding Command="self:CustomCommands.Exit" CanExecute="ExitCommand_CanExecute" Executed="ExitCommand_Executed" />
</Window.CommandBindings>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Menu>
<MenuItem Header="File">
<MenuItem Command="self:CustomCommands.Exit" />
</MenuItem>
</Menu>
<StackPanel Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Command="self:CustomCommands.Exit">Exit</Button>
</StackPanel>
</Grid>
</Window>
using System.Windows;
using System.Windows.Input;
namespace 命令
{
/// <summary>
/// MainWindow.xaml 的交互邏輯
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ExitCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void ExitCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
Application.Current.Shutdown();
}
}
public static class CustomCommands
{
public static readonly RoutedUICommand Exit = new RoutedUICommand
(
"Exit",
"Exit",
typeof(CustomCommands),
new InputGestureCollection()
{
new KeyGesture(Key.F4, ModifierKeys.Alt)
}
);
}
}
代碼分析:最大區別在於cs代碼實現了一個靜態類,類中有一個靜態字段。
靜態字段Exit的初始化RoutedUICommand構造函數,第一個參數爲命令的文本/標籤,第二個參數爲命令的名稱,第三個參數爲所有者類型,然後是InputGestureCollection,允許爲命令定義默認快捷方式(Alt + F4)
CommandBindings 綁定的就是這個靜態字段,button關聯的也是這個靜態字段。
通過示例可見,點擊button和點擊MenuItem,以及alt+f4三者的響應形式相同,這正是命令解決的最佳場景。