How to not focus element on application startup?

感情迁移 提交于 2020-01-05 05:41:07

问题


Simplest application possible:

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

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

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.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/41182664/how-to-not-focus-element-on-application-startup

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!