<Window x:Class="CommandTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:CommandTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid x:Name="aGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="236*"/>
<ColumnDefinition Width="559*"/>
</Grid.ColumnDefinitions>
<Button x:Name="abutton" Content="Button" HorizontalAlignment="Left" Margin="186.046,62,0,0" VerticalAlignment="Top" Width="75" Grid.Column="1"/>
<TextBox x:Name="aTextBox" HorizontalAlignment="Left" Height="23" Margin="186.046,126,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" Grid.Column="1"/>
</Grid>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
initializeCommand();
}
//声明并定义命令
private RoutedCommand clearCmd = new RoutedCommand("clear", typeof(MainWindow));
private void initializeCommand() {
//把命令赋值给发送者并指定快捷键
abutton.Command = clearCmd;
clearCmd.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Alt));
//指定命令目标
abutton.CommandTarget = aTextBox;
//创建命令关联
CommandBinding cb = new CommandBinding();
cb.Command = clearCmd;
cb.CanExecute += new CanExecuteRoutedEventHandler(cb_canExecute);
cb.Executed += new ExecutedRoutedEventHandler(cb_execute);
//把命令关联在外围控件上
aGrid.CommandBindings.Add(cb);
}
//探测命令是否被执行时,该命令被调用
void cb_canExecute(object sender, CanExecuteRoutedEventArgs e) {
if (string.IsNullOrEmpty(aTextBox.Text))
{
e.CanExecute = false;
}
else {
e.CanExecute = true;
}
//避免继续向上传降低程序性能
e.Handled = true;
}
//当命令到达目标后,此方法被调用
void cb_execute(object sender, ExecutedRoutedEventArgs e) {
aTextBox.Clear();
//避免继续向上传降低程序性能
e.Handled = true;
}
}
}
网友评论