繁体   English   中英

在Windows 8 Store应用程序中,在“进入/返回”按钮上移动到下一个控件

[英]Move to the next control on enter/return press in Windows 8 Store application

我有一个带有大量文本框的Windows 8商店应用程序。 当我按下键盘上的Enter键时,我希望将focues移动到下一个控件。

我怎样才能做到这一点?

谢谢

您可以处理TextBoxes上的KeyDown / KeyUp事件(取决于您是否要在按键的开头或结尾处转到下一个事件)。

示例XAML:

<TextBox KeyUp="TextBox_KeyUp" />

代码背后:

    private void TextBox_KeyUp(object sender, KeyRoutedEventArgs e)
    {
        TextBox tbSender = (TextBox)sender;

        if (e.Key == Windows.System.VirtualKey.Enter)
        {
            // Get the next TextBox and focus it.

            DependencyObject nextSibling = GetNextSiblingInVisualTree(tbSender);
            if (nextSibling is Control)
            {
                // Transfer "keyboard" focus to the target element.
                ((Control)nextSibling).Focus(FocusState.Keyboard);
            }
        }
    }

完整的示例代码,包括GetNextSiblingInVisualTree()辅助方法的代码: https//github.com/finnigantime/Samples/tree/master/examples/Win8Xaml/TextBox_EnterMovesFocusToNextControl

请注意,使用FocusState.Keyboard调用Focus()会在控件模板(例如Button)中显示带有这种矩形的元素周围的虚线焦点。 使用FocusState.Pointer调用Focus()不会显示焦点rect(您正在使用触摸/鼠标,因此您知道要与哪个元素进行交互)。

我对“GetNextSiblingInVisualTree”函数稍作改进。 此版本搜索下一个TextBox而不是下一个对象。

    private static DependencyObject GetNextSiblingInVisualTree(DependencyObject origin)
    {
        DependencyObject parent = VisualTreeHelper.GetParent(origin);

        if (parent != null)
        {
            int childIndex = -1;
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); ++i)
            {
                if (origin == VisualTreeHelper.GetChild(parent, i))
                {
                    childIndex = i;
                    break;
                }
            }

            for (int nextIndex = childIndex + 1; nextIndex < VisualTreeHelper.GetChildrenCount(parent); nextIndex++ )
            {
                DependencyObject currentObject = VisualTreeHelper.GetChild(parent, nextIndex);

                if( currentObject.GetType() == typeof(TextBox))
                {
                    return currentObject;
                }
            }
        }

        return null;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM