我使用 uwp navigation example作为我的应用程序导航的示例。我需要将焦点设置在 TextBox 上。我试了一下 uwp navigation example .对于 BasicPage,我添加了这段代码:
<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 没有获得焦点。我在一个“普通”的 Windows 通用应用程序中尝试了这段代码——它是有效的。你有什么建议?
最佳答案
这是因为在你调用了Test1.Focus之后,Focus函数在其他地方被调用了。
在AppShell.xaml.cs中,可以找到如下代码:
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();
}
上面的代码表示当你导航到一个页面时,它会订阅页面加载事件并将焦点设置在页面上。
您的代码在页面本身中订阅页面加载事件。并且您的代码将在 AppShell 中的 Page_Loaded 函数之前执行。所以你没有得到你想要的。
因此,如果您只是在 Page_Loaded 函数中注释掉 ((Page)sender).Focus(FocusState.Programmatic);
。你会得到你想要的。我不确定那条线的确切目的是什么。但一切似乎都很好。
如果您在注释掉该行后确实发现问题,我们也可以解决。加载事件后,在 LayoutUpdated 事件中调用一次焦点函数。
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;
}
}
希望对您有所帮助。
关于c# - Uwp导航示例和焦点控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33609832/