在 UWP 中禁用控制焦点

Disable focus for control in UWP

我正在为带触摸屏的 RPi3 构建 UWP 应用程序。我有一个文本框,我将重点放在页面加载上。如果用户触摸页面上的另一个控件(两个特定按钮除外),我不想失去焦点。我正在使用此文本框进行扫描仪输入。

我已经尝试禁用我不想获得焦点的控件的不同属性:

AllowFocusOnInteraction="False" IsDoubleTapEnabled="False" IsHitTestVisible="False" IsHoldingEnabled="False" IsRightTapEnabled="False" IsTapEnabled="False"

但是如果我按下这些控件中的任何一个,文本框仍然会失去焦点。

我还尝试了 textbox_LostFocus 的事件处理程序来重新赋予它焦点,但是这会阻止用户单击用户需要单击的 2 个按钮中的一个(唯一应该获得焦点的控件) 因为 textbox_LostFocus 事件再次触发以在 button_Click 事件触发之前将焦点设置回文本框。

在 winform 中,我会禁用制表位 属性。对 UWP 有什么想法吗?

提前致谢。

在您不想关注的按钮上,尝试将 IsTabStop 属性 设置为 false

如果你想让你的TextBox不失去焦点,你应该可以通过LostFocus事件中的Focus方法设置焦点。

如您所知,如果我们在 LostFocus 事件中设置 Focus,则不会触发 Click 事件。

所以我们应该能够在您的 LostFocus 事件中添加一个 if,当用户单击 Button 时,Text 可能会失去焦点。为此,我们可以添加 PointerEntered 事件和 ButtonPointerExited。在PointerEntered事件中,我们可以设置setFocus.

的值

例如:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button Content="Click" AllowFocusOnInteraction="False" IsDoubleTapEnabled="False" IsHitTestVisible="False" IsHoldingEnabled="False" IsRightTapEnabled="False" IsTapEnabled="False"></Button>
        <TextBox Name="MyText" Text="Hello" LostFocus="MyText_LostFocus"></TextBox>
        <Button Name="MyButton" PointerEntered="MyButton_PointerEntered" PointerExited="MyButton_PointerExited" Click="Button_Click" Content="Submit"></Button>
    </StackPanel>
</Grid>

后面的代码:

private bool setFocus = true;

private void MyText_LostFocus(object sender, RoutedEventArgs e)
{
    if (setFocus == true)
    {
        MyText.Focus(FocusState.Programmatic);
    }
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyButton.Focus(FocusState.Programmatic);
}

private void MyButton_PointerEntered(object sender, PointerRoutedEventArgs e)
{
    setFocus = false;
}

private void MyButton_PointerExited(object sender, PointerRoutedEventArgs e)
{
    setFocus = true;
}

IsEnabled property 就是这样做的。如果您不喜欢 "greyed out" 外观,您可以更改控件模板。

我遇到了和你类似的问题。

我的解决方案是将根视觉元素 (ScrollViewer) 属性 AllowFocusOnInteraction 设置为 false:

var rootScrollViewer = GetVisualRootElement();
rootScrollViewer.AllowFocusOnInteraction = false;

我的可视化树是这样的:ScrollViewer->Border->Frame->MainPage->StackPanel->etc...

下一步是将 AllowFocusOnInteraction 设置为 True 以允许控制交互(TextBox、CheckBox 等...)。

此致,

亚当