代码之家  ›  专栏  ›  技术社区  ›  Zaz

我可以使用箭头键而不是制表符在WPF组合框中导航进出吗?

  •  2
  • Zaz  · 技术社区  · 15 年前

    我有一个wpf用户控件,它在一行中包含一个组合框和一个文本框。目前,在组件之间移动的唯一方法是在它们之间使用制表符,但我也希望能够使用左右箭头键从组合框切换到文本框。

    这并不像仅仅在keyup事件上触发事件处理程序那么简单。

    void ComboKeyUp( object sender, KeyEventArgs e )
    {
        if( e.Key == Key.Right)
        {
            e.Handled = true;
            textbox.Focus();
        }
    }
    

    …因为组合将更改值,尽管事件被报告为已处理。

    有没有一种方法不同时分解组合框中项目的向上/向下选择?

    2 回复  |  直到 15 年前
        1
  •  2
  •   angordeyev    15 年前

    <ComboBox Width="100" Height="25"  PreviewKeyDown="ComboboxPreviewKeyDown">
      <ComboBox.Items> 
        <TextBox Text="Item 1"/>
        <TextBox Text="Item 2"/>
        <TextBox Text="Item 3"/>
      </ComboBox.Items>
    </ComboBox>
    

        private void ComboboxPreviewKeyDown(object sender, KeyEventArgs e)
        {
            Action<FocusNavigationDirection> moveFocus = focusDirection => {
                e.Handled = true;
                var request = new TraversalRequest(focusDirection);        
                var focusedElement = Keyboard.FocusedElement as UIElement;
                if (focusedElement != null)
                    focusedElement.MoveFocus(request);
            };
    
            if (e.Key == Key.Down)
                moveFocus(FocusNavigationDirection.Next);
            else if (e.Key == Key.Up)
                moveFocus(FocusNavigationDirection.Previous); 
        }
    

        2
  •  1
  •   Zaz    15 年前

    推荐文章