WPF tab order with custom controls?

前端 未结 5 1210
别那么骄傲
别那么骄傲 2021-01-14 13:46

I have a WPF page that contains several out of the box controls with the tab order set.

I have a custom control (NumericSpinner) that contains: border/grid/text box/

5条回答
  •  隐瞒了意图╮
    2021-01-14 13:54

    HaxElit's answer works unless we want to use labels to focus our control by Alt + hotkey like this:

    
    
    
    

    So my final solution is as follows:

    static NumericSpinner()
    {
        // Next line prevents focusing our wrapper parent control. The problem with that is that
        // it prevents Label controls to select our control by Alt+
        //FocusableProperty.OverrideMetadata(typeof(NumericSpinner), new FrameworkPropertyMetadata(false));
    
        // Next line specifies that the children controls have their own tab subtree so a deep
        // traversal is performed when our control is focused
        KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(NumericSpinner), new FrameworkPropertyMetadata(KeyboardNavigationMode.Local));
    }
    
    // our wrapper control is focused invisibly. We must relocate the focus.
    protected override void OnGotFocus(RoutedEventArgs e)
    {
        base.OnGotFocus(e);
    
        // Next line moves the focus either forward (to out first inner child)
        // or backward if Shift+TAB is pressed (to the previous control)
        MoveFocus(new TraversalRequest(Keyboard.IsKeyDown(Key.Tab) && (Keyboard.Modifiers & ModifierKeys.Shift) != 0 ? FocusNavigationDirection.Previous : FocusNavigationDirection.Next));
    }
    

提交回复
热议问题