将 Enter 解释为选项卡 WPF

发布于 2024-07-21 06:05:52 字数 144 浏览 7 评论 0原文

我想在整个 WPF 应用程序中将 Enter 键解释为 Tab 键,即在我的应用程序中的任何位置,当用户按 Enter 时,我想聚焦下一个可聚焦控件,但按钮聚焦时除外。 在应用程序生命周期中有什么办法可以做到这一点吗? 谁能给我举个例子吗?
非常感谢!

I want to interpret Enter key as Tab key in whole my WPF application, that is, everywhere in my application when user press Enter I want to focus the next focusable control,except when button is focused. Is there any way to do that in application life circle? Can anyone give me an example?
Thanks a lot!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

旧人 2024-07-28 06:05:52

您可以使用我的 EnterKeyTraversal 附加属性代码如果你喜欢。 将其添加到 WPF 窗口上的顶级容器中,其中的所有内容都会将 Enter 视为选项卡:

<StackPanel my:EnterKeyTraversal.IsEnabled="True">
    ...
</StackPanel>

You can use my EnterKeyTraversal attached property code if you like. Add it to the top-level container on a WPF window and everything inside will treat enter as tab:

<StackPanel my:EnterKeyTraversal.IsEnabled="True">
    ...
</StackPanel>
澉约 2024-07-28 06:05:52

根据 Richard Aguirre 的答案,该答案比所选的易于使用的答案更好,恕我直言,您可以通过简单地将 Grid 更改为 UIElement 来使其更加通用。

要在整个项目中更改它,您需要执行以下操作

  • 在 App.xaml.cs 中:

     protected override void OnStartup(StartupEventArgs e) 
       {            
           EventManager.RegisterClassHandler(typeof(UIElement), UIElement.PreviewKeyDownEvent, new KeyEventHandler(Grid_PreviewKeyDown)); 
           基础.OnStartup(e); 
       } 
    
       private void Grid_PreviewKeyDown(对象发送者,System.Windows.Input.KeyEventArgs e) 
       { 
           var uie = e.OriginalSource 作为 UIElement; 
    
           if (e.Key == Key.Enter) 
           { 
               e.已处理=真; 
               uie.MoveFocus( 
               新的遍历请求( 
               FocusNavigationDirection.Next)); 
           } 
       } 
      
  • 编译。
    并做到了。 现在您可以使用类似 tab 的 Enter 功能。
    注意:这适用于网格中的元素

Based on Richard Aguirre's answer, which is better than the selected answer for ease of use, imho, you can make this more generic by simply changing the Grid to a UIElement.

To change it in whole project you need to do this

  • In App.xaml.cs:

     protected override void OnStartup(StartupEventArgs e)
     {           
         EventManager.RegisterClassHandler(typeof(UIElement), UIElement.PreviewKeyDownEvent, new KeyEventHandler(Grid_PreviewKeyDown));
         base.OnStartup(e);
     }
    
     private void Grid_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
     {
         var uie = e.OriginalSource as UIElement;
    
         if (e.Key == Key.Enter)
         {
             e.Handled = true;
             uie.MoveFocus(
             new TraversalRequest(
             FocusNavigationDirection.Next));
         }
     }
    
  • Compile.
    And done it. Now you can use enter like tab.
    Note: This work for elements in the grid

夏花。依旧 2024-07-28 06:05:52

我通过在 XAML 中向某些元素(按钮、组合框或任何我想忽略回车键遍历的元素)添加 FrameworkElement.Tag(其值为 IgnoreEnterKeyTraversal)来解决 woodyiii 的问题。 然后我寻找这个标签& 附加财产中的价值。 就像这样:

    if (e.Key == Key.Enter)
    {
        if (ue.Tag != null && ue.Tag.ToString() == "IgnoreEnterKeyTraversal")
        {
            //ignore
        }
        else
        {
            e.Handled = true;
            ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }

I got around woodyiii's issue by adding a FrameworkElement.Tag (whose value is IgnoreEnterKeyTraversal) to certain elements (buttons, comboboxes, or anything I want to ignore the enter key traversal) in my XAML. I then looked for this tag & value in the attached property. Like so:

    if (e.Key == Key.Enter)
    {
        if (ue.Tag != null && ue.Tag.ToString() == "IgnoreEnterKeyTraversal")
        {
            //ignore
        }
        else
        {
            e.Handled = true;
            ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }
感悟人生的甜 2024-07-28 06:05:52

woodyiii,UIElement 中有一个名为 PredictFocus() 的函数,从名字就知道它的作用,那么你可以检查该元素是否启用,以便移动重点还是不...

woodyiii, There is a function in the UIElement called PredictFocus() which by its name know its function, then you can check if that element is enabled or not so as to move the focus to it or not...

青芜 2024-07-28 06:05:52

这是马特·汉密尔顿的代码,如果有人想知道,因为他的网站显然已关闭:

public class EnterKeyTraversal
{
    public static bool GetIsEnabled(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsEnabledProperty);
    }

    public static void SetIsEnabled(DependencyObject obj, bool value)
    {
        obj.SetValue(IsEnabledProperty, value);
    }

    static void ue_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        var ue = e.OriginalSource as FrameworkElement;

        if (e.Key == Key.Enter)
        {
            e.Handled = true;
            ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }

    private static void ue_Unloaded(object sender, RoutedEventArgs e)
    {
        var ue = sender as FrameworkElement;
        if (ue == null) return;

        ue.Unloaded -= ue_Unloaded;
        ue.PreviewKeyDown -= ue_PreviewKeyDown;
    }

    public static readonly DependencyProperty IsEnabledProperty =
        DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),

        typeof(EnterKeyTraversal), new UIPropertyMetadata(false, IsEnabledChanged));

    static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var ue = d as FrameworkElement;
        if (ue == null) return;

        if ((bool)e.NewValue)
        {
            ue.Unloaded += ue_Unloaded;
            ue.PreviewKeyDown += ue_PreviewKeyDown;
        }
        else
        {
            ue.PreviewKeyDown -= ue_PreviewKeyDown;
        }
    }
}

Here is Matt Hamilton's code, if anyone is wondering since his site is down apparently:

public class EnterKeyTraversal
{
    public static bool GetIsEnabled(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsEnabledProperty);
    }

    public static void SetIsEnabled(DependencyObject obj, bool value)
    {
        obj.SetValue(IsEnabledProperty, value);
    }

    static void ue_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        var ue = e.OriginalSource as FrameworkElement;

        if (e.Key == Key.Enter)
        {
            e.Handled = true;
            ue.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }

    private static void ue_Unloaded(object sender, RoutedEventArgs e)
    {
        var ue = sender as FrameworkElement;
        if (ue == null) return;

        ue.Unloaded -= ue_Unloaded;
        ue.PreviewKeyDown -= ue_PreviewKeyDown;
    }

    public static readonly DependencyProperty IsEnabledProperty =
        DependencyProperty.RegisterAttached("IsEnabled", typeof(bool),

        typeof(EnterKeyTraversal), new UIPropertyMetadata(false, IsEnabledChanged));

    static void IsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var ue = d as FrameworkElement;
        if (ue == null) return;

        if ((bool)e.NewValue)
        {
            ue.Unloaded += ue_Unloaded;
            ue.PreviewKeyDown += ue_PreviewKeyDown;
        }
        else
        {
            ue.PreviewKeyDown -= ue_PreviewKeyDown;
        }
    }
}
揪着可爱 2024-07-28 06:05:52

另一种更开/关的实现方法是使用行为:

public class TextBoxEnterFocusesNextBehavior :
    Behavior<TextBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.PreviewKeyDown += AssociatedObjectOnPreviewKeyDown;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.PreviewKeyDown -= AssociatedObjectOnPreviewKeyDown;
        base.OnDetaching();
    }

    private void AssociatedObjectOnPreviewKeyDown(object sender, KeyEventArgs args)
    {
        if (args.Key != Key.Enter) { return; }

        args.Handled = true;
        AssociatedObject.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }
}

用法示例:

<UserControl xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
             xmlns:behaviors="clr-namespace:Your.Namespace.To.Behaviors"
             ...>
    <DockPanel>
        <TextBox x:Name="TextBoxWithBehavior"
                 DockPanel.Dock="Top">
            <b:Interaction.Behaviors>
                <behaviors:TextBoxEnterFocusesNextBehavior />
            </b:Interaction.Behaviors>
        </TextBox>
        <TextBox x:Name="TextBoxWithoutBehavior"
                 DockPanel.Dock="Top" />
        <TextBox x:Name="AnotherTextBoxWithBehavior"
                 DockPanel.Dock="Top">
            <b:Interaction.Behaviors>
                <behaviors:TextBoxEnterFocusesNextBehavior />
            </b:Interaction.Behaviors>
        </TextBox>
    </DockPanel>
</UserControl>

Another, a more on/off implementation approach would be to use behaviors:

public class TextBoxEnterFocusesNextBehavior :
    Behavior<TextBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.PreviewKeyDown += AssociatedObjectOnPreviewKeyDown;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.PreviewKeyDown -= AssociatedObjectOnPreviewKeyDown;
        base.OnDetaching();
    }

    private void AssociatedObjectOnPreviewKeyDown(object sender, KeyEventArgs args)
    {
        if (args.Key != Key.Enter) { return; }

        args.Handled = true;
        AssociatedObject.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }
}

Usage example:

<UserControl xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
             xmlns:behaviors="clr-namespace:Your.Namespace.To.Behaviors"
             ...>
    <DockPanel>
        <TextBox x:Name="TextBoxWithBehavior"
                 DockPanel.Dock="Top">
            <b:Interaction.Behaviors>
                <behaviors:TextBoxEnterFocusesNextBehavior />
            </b:Interaction.Behaviors>
        </TextBox>
        <TextBox x:Name="TextBoxWithoutBehavior"
                 DockPanel.Dock="Top" />
        <TextBox x:Name="AnotherTextBoxWithBehavior"
                 DockPanel.Dock="Top">
            <b:Interaction.Behaviors>
                <behaviors:TextBoxEnterFocusesNextBehavior />
            </b:Interaction.Behaviors>
        </TextBox>
    </DockPanel>
</UserControl>
自此以后,行同陌路 2024-07-28 06:05:52

我的解决方案:

public class MoveToNext : TriggerAction<DependencyObject>
{
    protected override void Invoke(object parameter)
    {
        if (parameter is RoutedEventArgs routedEventArgs && routedEventArgs.OriginalSource is FrameworkElement element)
        {
            routedEventArgs.Handled = true;
            element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }
}

用法:

<StackPanel>
    <i:Interaction.Triggers>
        <i:KeyTrigger Key="Return">
            <util:MoveToNext/>
        </i:KeyTrigger>
    </i:Interaction.Triggers>
<!-- put your controls here -->
</StackPanel>

如果您希望将行为仅附加到一个控件而不是布局器中的所有控件,只需将

My solution:

public class MoveToNext : TriggerAction<DependencyObject>
{
    protected override void Invoke(object parameter)
    {
        if (parameter is RoutedEventArgs routedEventArgs && routedEventArgs.OriginalSource is FrameworkElement element)
        {
            routedEventArgs.Handled = true;
            element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }
}

Usage:

<StackPanel>
    <i:Interaction.Triggers>
        <i:KeyTrigger Key="Return">
            <util:MoveToNext/>
        </i:KeyTrigger>
    </i:Interaction.Triggers>
<!-- put your controls here -->
</StackPanel>

If you want the behavior to be attached to only one control instead of all controls within a layouter, simply add the <i:Interaction.Triggers block to that specific control.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文