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

Sun*_*Sun 5 c# keypress windows-8 winrt-xaml

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

我怎样才能做到这一点?

谢谢

Pat*_*gan 5

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

示例XAML:

<TextBox KeyUp="TextBox_KeyUp" />
Run Code Online (Sandbox Code Playgroud)

代码背后:

    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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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