首页 > 解决方案 > 使用“Enter”导航将按钮集中在其他页面上

问题描述

我有一个“登录页面”和一个“内容页面”。登录页面由 aPasswordBox和 a组成Button。当在 中单击按钮或按下 Enter 键时PasswordBox,我希望程序导航到下一页。使用按钮导航工作正常,但是当页面由于按下回车键而改变时,Button下一页上的焦点。如何禁用/避免这种行为?

“聚焦”按钮:在此处输入图像描述


主页.xaml

<Page
    x:Class="TabNavigation.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TabNavigation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <StackPanel>
            <PasswordBox x:Name="textBox" KeyDown="HandleTextBox_KeyDown"/>
            <Button x:Name="loginButton" Content="Einloggen" Click="HandleLoginButton_Click"/>
        </StackPanel>
    </Grid>
</Page>

MainPage.xaml.cs

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;

namespace TabNavigation {
    public sealed partial class MainPage : Page {
        public MainPage() {
            this.InitializeComponent();
        }

        private void HandleTextBox_KeyDown(object sender, KeyRoutedEventArgs e) {
            if(e.Key == Windows.System.VirtualKey.Enter) {
                this.Frame.Navigate(typeof(ContentPage));
            }
        }

        private void HandleLoginButton_Click(object sender, RoutedEventArgs e) {
            this.Frame.Navigate(typeof(ContentPage));
        }
    }
}

内容页面.xaml

<Page
    x:Class="TabNavigation.ContentPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TabNavigation"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <StackPanel>
            <Button>Test</Button>
        </StackPanel>
    </Grid>
</Page>

标签: c#uwp

解决方案


您可以取消焦点GettingFocus

 <Button GettingFocus="Button_GettingFocus">Test</Button>
private void Button_GettingFocus(UIElement sender, GettingFocusEventArgs args)
 {
   args.Cancel = true;
 }

老答案:

你有几个选择:

  • 禁用对按钮的关注IsTabStop=false
  • 更改TabIndex为比其他元素更大的整数。
  • 将焦点从您的代码转移到其他内容:otherControl.Focus(FocusState.Programmatic);

推荐阅读