如何对TextBox中的特定按键执行操作?

问题描述:

我有一个文本框的WPF窗口。我想要检测用户何时按下Enter键或Tab键。当按下这些键中的任何一个时,我想绑定到视图模型中的操作。有人能告诉我如何做到这一点吗?如何对TextBox中的特定按键执行操作?

处理KeyDown事件。

<TextBox KeyDown="TextBox_KeyDown"/> 
private void TextBox_KeyDown(object sender, KeyEventArgs e) 
{ 
    switch (e.Key) 
    { 
     case Key.Enter: 
      vw.Method1(); 
      break; 
     case Key.Tab: 
      vw.Method2(); 
      break; 
     default: 
    } 
} 

或者使用命令:

public static class Commands 
{ 
    public static RoutedCommand Command1 = new RoutedCommand(); 
    public static RoutedCommand Command2 = new RoutedCommand(); 
} 
<TextBox> 
    <TextBox.CommandBindings> 
     <CommandBinding Command="{x:Static local:Commands.Command1}" 
         Executed="Command1_Executed" CanExecute="Command1_CanExecute"/> 
     <CommandBinding Command="{x:Static local:Commands.Command2}" 
         Executed="Command2_Executed" CanExecute="Command2_CanExecute"/> 
    </TextBox.CommandBindings> 
    <TextBox.InputBindings> 
     <KeyBinding Key="Enter" Command="{x:Static local:Commands.Command1}"/> 
     <KeyBinding Key="Tab" Command="{x:Static local:Commands.Command2}"/> 
    </TextBox.InputBindings> 
</TextBox> 

如果你还没有使用过的命令务必阅读this overview之前。

+0

请注意:Tab用于键盘导航(聚焦下一个UI控件),这是使程序可访问所需的。 – RandomEngy 2011-04-05 16:11:38

+0

确实如此,但是在文本框中,它也可以具有与导航不同的功能,因此在此处使用它可能是不容易的。也许应该有一个选项来关闭它,但有可能是某些地方的指导方针... – 2011-04-05 16:14:39