Uwp navigation example and focus on management

I use the uwp navigation example as an example to navigate my application. I need to focus on TextBox. I tried this using uwp navigation example . For BasicPage, I add this code:

<StackPanel Orientation="Vertical"> <TextBox x:Name="Test" /> <TextBox x:Name="Test1" /> </StackPanel> public BasicPage() { this.InitializeComponent(); this.Loaded += BasicPage_Loaded; } private void BasicPage_Loaded(object sender, RoutedEventArgs e) { Test1.Focus(FocusState.Programmatic); } 

Test1 does not receive focus. I try this code in a "regular" universal Windows application - this is the job. What do you advise?

+5
source share
2 answers

This is because the Focus function is called elsewhere after calling 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 code above means that when you go to the page, he will sign the event loaded by the page and adjust the focus on the page.

Your code will sign the event loaded by the page on the page itself. And your code will be executed before the Page_Loaded function in AppShell. So you have not received what you want.

So, if you just comment out ((Page)sender).Focus(FocusState.Programmatic); in the function Page_Loaded. You will get what you want. I do not know what the purpose of this line is. But everything seems good.

If you notice something wrong after the comments of this line, we can also process it. Call the focus function once in the LayoutUpdated event after the 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 helps you.

+6
source

if you want to focus the text field programmatically. Prevent the keyboard so that the layoutupdate event will not fire. You can do something like then in the page_loaded event do Test1.Focus (FocusState.Programmatic);

0
source

Source: https://habr.com/ru/post/1235541/


All Articles