如何不将元素集中在应用程序启动上? [英] How to not focus element on application startup?

查看:27
本文介绍了如何不将元素集中在应用程序启动上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最简单的应用程序:

<Page
    x:Class="TestApp.MainPage"
    ...>
    <Grid>
        <TextBox />
    </Grid>
</Page>

问题:有没有什么优雅的方法可以防止在应用程序启动时在 TextBox 中设置光标(焦点)?

Question: is there any elegant way to prevent the cursor (focus) from being set in the TextBox on application start up?

扩展:我真正的问题是当 TextBox 获得焦点时我有一个 PopUp 被打开.如果我单击 PopUp 中的一个元素,它应该关闭,但由于 TextBox 是我页面中的第一个可聚焦元素,它会自动获得焦点,因此 PopUp 会立即再次打开.我认为问题的核心就是上面的例子.

To expand: My real issue is that I have a PopUp that is opened when the TextBox receives focus. If I click on an element in my PopUp it should close, but since the TextBox is the first focusable element in my page it automatically receives focus and thus the PopUp immediately opens again. The core of the problem I think is represented by the example above.

推荐答案

焦点由各种属性管理,例如 IsTabStopTabIndexIsHitTestVisibleFocusManager 类.有内置功能可以在窗口激活后聚焦第一个可聚焦元素,并且此行为通常不可自定义.

Focus is managed by various properties like IsTabStop, TabIndex, IsHitTestVisible, and the FocusManager class. There is built-in functionality to focus the first focusable element once the window is activated, and this behavior is generally not customizable.

我们可以指定一个不同的元素来获得焦点,而不是像页面本身这样的文本框:

We could designate a different element to be focused instead of the textbox like, say, the page itself:

<Page IsTabStop="True">
    <TextBox/>
</Page>

这是因为页面获得了初始焦点而不是文本框,但现在页面参与了标签行为,这有点不受欢迎.

This works in that the page gets initial focus instead of the textbox, but now the page participates in tabbing behavior, which is slightly undesirable.

通常,当您单击焦点控件外时,框架会将焦点设置到 RootScrollViewer,即使 RootScrollViewer 不是制表位(因此它无法通过 Tab 键接收焦点).如果我们可以在页面加载时聚焦 RootScrollViewer,框架将检测某物有焦点并且不会尝试聚焦第一个元素.

Typically the framework will set focus to the RootScrollViewer when you click out of a focused control, even though the RootScrollViewer isn't a tab stop (so it can't receive focus by tabbing). If we can focus the RootScrollViewer upon page load, the framework will detect that something has focus and won't attempt to focus the first element.

<Page Loaded="onPageLoaded">
    <TextBox/>
</Page>

private ScrollViewer getRootScrollViewer()
{
    DependencyObject el = this;
    while (el != null && !(el is ScrollViewer))
    {
        el = VisualTreeHelper.GetParent(el);
    }

    return (ScrollViewer)el;
}

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

这是我所知道的防止文本框自动获得焦点的最优雅"的方式.

This is the most "elegant" way that I know to prevent the textbox from getting focused automatically.

这篇关于如何不将元素集中在应用程序启动上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆