Хотя методы Skeets и Abe работают, они являются взломами. Вы можете просто указать, что команда WPF также должна вызываться так называемой InputGesture, в данном случае KeyGesture ("enter" или "escape"). Вы можете установить область действия этой KeyGestures, поместив CommandBinding для команды на соответствующем уровне в Visual Tree. Как это:
<Window x:Class="CommandSpike.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CommandSpike"
Title="Window1" Height="300" Width="300">
<StackPanel>
<Grid>
<Grid.CommandBindings>
<CommandBinding x:Name="EnterBinding"
Command="{x:Static local:Commands.EnterCommand}"
CanExecute="CommandBinding_CanExecute"
Executed="EnterBinding_Executed"/>
<CommandBinding x:Name="CancelBinding"
Command="{x:Static local:Commands.CancelCommand}"
CanExecute="CommandBinding_CanExecute"
Executed="CancelBinding_Executed"/>
</Grid.CommandBindings>
<TextBox>
Press Enter or Cancel when I have focus...
</TextBox>
</Grid>
<TextBox Margin="0,4">
Pressing Enter or Cancel does nothing while I have focus!
</TextBox>
</StackPanel>
</Window>
using System.Windows;
using System.Windows.Input;
namespace CommandSpike
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void EnterBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Enter");
}
private void CancelBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Cancel");
}
}
}
using System.Windows.Input;
namespace CommandSpike
{
public static class Commands
{
public static RoutedUICommand EnterCommand { get;private set; }
public static RoutedUICommand CancelCommand { get; private set; }
static Commands()
{
EnterCommand=new RoutedUICommand("Enter",
"EnterCommand",
typeof(Commands));
EnterCommand.InputGestures.Add(
new KeyGesture(Key.Enter)
);
CancelCommand=new RoutedUICommand("Cancel",
"CancelCommand",
typeof(Commands));
CancelCommand.InputGestures.Add(
new KeyGesture(Key.Escape)
);
}
}
}