一般我們針對control比較常會使用event,例如有個button,
點了button後要執行什麼樣的動作,用event就可以完成。
但有時候某些動作比較特別,像是有個貼上的按鈕、crtl+v、toolbar有貼上的功能…
這種情況下我們就能使用command來完成,.net framework已經提供了許多的command供我們使用
例如,一個簡單的cut、paste功能
<DockPanel>
<WrapPanel DockPanel.Dock="Top" Margin="3">
<Button Command="ApplicationCommands.Cut"
CommandTarget="{Binding ElementName=txtEditor}"
Width="60">_Cut</Button>
<Button Command="ApplicationCommands.Paste"
CommandTarget="{Binding ElementName=txtEditor}" Width="60"
Margin="3,0">_Paste</Button>
</WrapPanel>
<TextBox AcceptsReturn="True" Name="txtEditor"
/>
</DockPanel>
當有選取文字時,cut才會變enable…之類的動作,WPF都已經幫我們設計好了。
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.New"
Executed="NewCommand_Executed"
CanExecute="NewCommand_CanExecute" />
</Window.CommandBindings>
<StackPanel
HorizontalAlignment="Center" VerticalAlignment="Center">
<Button
Command="ApplicationCommands.New">New</Button>
</StackPanel>
設計一個ApplicationCommands.New的command,注意到有兩個重要的method,
Executed - 用來實作這個command要如何執行
CanExecuted - 用來實作這個command現在允不允許被執行
private void NewCommand_CanExecute(object
sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true; //
這裡設成ture,所以command永遠都是可以被執行的狀態
}
private void NewCommand_Executed(object
sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("The New command was invoked");
}
當然我們也可以自行設計command
<Window
x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:self="clr-namespace:WpfApplication1"
Title="Say Hello" Height="350"
Width="525">
<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>
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
{
// 這裡定義了Exit command,並且按下Alt + F4也可以執行Exit的動作
public static readonly RoutedUICommand Exit = new RoutedUICommand
(
"Exit",
"Exit",
typeof(CustomCommands),
new
InputGestureCollection()
{
new KeyGesture(Key.F4,
ModifierKeys.Alt)
}
);
}