Uwp navigation example and focusing on control

前端 未结 2 457
再見小時候
再見小時候 2021-01-12 09:06

I use uwp navigation example as an example for my application navigation. I need to set the focus on TextBox. I try it on uwp navigation example. For BasicPage I add this co

相关标签:
2条回答
  • 2021-01-12 09:55

    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.

    0 讨论(0)
  • 2021-01-12 09:59

    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);

    0 讨论(0)
提交回复
热议问题