【问题标题】:how to fire an event when the TAB key is pressed in wpf c#?在 wpf c# 中按下 TAB 键时如何触发事件?
【发布时间】:2014-07-25 23:21:15
【问题描述】:

当我按 Tab 或 shift+tab 键时显示消息,但我只想在按 Tab 键而不是 shift+tab 键时显示此消息。 仅当我在 Wpf C# 中使用 previewkeydown 事件按 Tab 键时如何定义此事件?

private void txtH_PreviewKeyDown(object sender, KeyEventArgs e)
{
   if (e.Key == Key.Tab)
   {
        MessageBox.Show("Tab");
   }
}

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    您可以执行类似的检查

    if ((!e.KeyboardDevice.IsKeyDown(Key.LeftShift)) 
        && (!e.KeyboardDevice.IsKeyDown(Key.RightShift)) 
        && e.KeyboardDevice.IsKeyDown(Key.Tab))
    

    或者你可以做一个检查

    if (!(e.KeyboardDevice.Modifiers == ModifierKeys.Shift)
        && e.KeyboardDevice.IsKeyDown(Key.Tab))
    

    【讨论】:

    • 我认为第一个 if 语句中的括号有问题。你有 7 个左括号,但只有 6 个右括号。
    • 去掉了多余的括号 Nate
    【解决方案2】:

    WPF 最好不要用于像 Winforms 这样的事件驱动方式。最好将 MVVM 模式与命令结合使用来分离表示和业务逻辑问题 - 这是 WPF 最强大的地方。

    这样做时,您可以在您的视图的 XAML 文件中定义 InputBinding 派生的 XAML 元素,并使用您的 ViewModel 中的 Command 属性指定要运行的 Command

    例如

    <KeyBinding Command="{Binding ShowMessageCommand}" Key="Tab" />
    <KeyBinding Command="{Binding ShowMessageCommand}" Modifiers="Shift" Key="Tab" />
    

    【讨论】:

    猜你喜欢
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多