Wpf 如何对文本框中的某些按键执行操作?
我有一个带有文本框的WPF窗口。我想检测用户何时按下Enter键或Tab键。当按下这两个键中的任何一个时,我希望绑定到视图模型中的动作。有人能告诉我怎么做吗?处理Wpf 如何对文本框中的某些按键执行操作?,wpf,textbox,Wpf,Textbox,我有一个带有文本框的WPF窗口。我想检测用户何时按下Enter键或Tab键。当按下这两个键中的任何一个时,我希望绑定到视图模型中的动作。有人能告诉我怎么做吗?处理KeyDown事件 <TextBox KeyDown="TextBox_KeyDown"/> 或使用命令: public static class Commands { public static RoutedCommand Command1 = new RoutedCommand(); public st
KeyDown
事件
<TextBox KeyDown="TextBox_KeyDown"/>
或使用命令:
public static class Commands
{
public static RoutedCommand Command1 = new RoutedCommand();
public static RoutedCommand Command2 = new RoutedCommand();
}
如果您以前没有使用过命令,请务必阅读。请注意:Tab用于键盘导航(聚焦下一个UI控件),这是使程序可访问所需的。是的,但在文本框中,它也可以具有与导航不同的功能,因此在此处使用它可能是情有可原的。也许应该有一个选项来关闭它,但是,可能有一些指导方针的地方。。。
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>