Uwp navigation example and focusing on control

蹲街弑〆低调 提交于 2019-11-30 19:50:21

It is because Focus function gets called in other place after you call the Test1.Focus.

In AppShell.xaml.cs, you can find the following code:

private void OnNavigatedToPage(object sender, NavigationEventArgs e)
{
    // After a successful navigation set keyboard focus to the loaded page
    if (e.Content is Page && e.Content != null)
    {
        var control = (Page)e.Content;
        control.Loaded += Page_Loaded;
    }
}

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    ((Page)sender).Focus(FocusState.Programmatic);
    ((Page)sender).Loaded -= Page_Loaded;
    this.CheckTogglePaneButtonSizeChanged();
}

The above code means when you navigate to a page, it will subscribe the page loaded event and set the focus on page.

Your code subscribe the page loaded event in the page itself. And your code will be executed before the Page_Loaded function in AppShell. So you didn't get what you want.

So if you simply comment out ((Page)sender).Focus(FocusState.Programmatic); in the Page_Loaded function. You will get what you want. I am not sure what's the exact purpose of that line. But everything seems good.

If you do find something wrong after comment out that line, we can also work it around. Call the focus function once in LayoutUpdated event after loaded event.

public sealed partial class BasicPage : Page
{
    bool bAfterLoaded = false;
    public BasicPage()
    {
        this.InitializeComponent();
        this.Loaded += BasicPage_Loaded;
        this.LayoutUpdated += BasicPage_LayoutUpdated;
    }

    private void BasicPage_LayoutUpdated(object sender, object e)
    {
        if (bAfterLoaded)
        {
            Test1.Focus(FocusState.Programmatic);
            bAfterLoaded = !bAfterLoaded;
        }
    }

    private void BasicPage_Loaded(object sender, RoutedEventArgs e)
    {
        bAfterLoaded = !bAfterLoaded;
    }
}

Hope this can help you.

if you want to focus a textbox programatically. Prevent keyboarddisplay so layoutupdate event wont fire. You can do something like then in page_loaded event do Test1.Focus(FocusState.Programmatic);

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