当控件变得可见时以编程方式设置焦点

Programmatically set focus when a control becomes visible

我有一个 AutoSuggestBox,它只在我点击一个按钮时显示。当 AutoSuggestBox 变得可见时,它也应该获得焦点。

我尝试了很多方法,但 none 方法奏效了。

我手上的代码:

 <AutoSuggestBox x:Name="AutoSearchBar" 
      HorizontalAlignment="Right" 
      VerticalAlignment="Center" 
      PlaceholderText="Text to find" 
      Visibility="Collapsed"/>

 <Button x:Name="searchButton" 
      Visibility="Visible" 
      HorizontalAlignment="Right"
      FontFamily="Segoe MDL2 Assets" 
      Background="Red"
      Content="&#xE094;"
      Click="searchButton_Click"/>

隐藏代码:

  private void searchButton_Click(object sender, RoutedEventArgs e)
  {
      AutoSearchBar.Visibility = Visibility.Visible;
      searchButton.Visibility = Visibility.Collapsed;
  }

我试图将它放在代码隐藏中 searchButton_Click,但是 AutoSearchBar 控件只出现并且没有焦点。

         AutoSearchBar.Focus(FocusState.Keyboard);
         AutoSearchBar.Focus(FocusState.Pointer);
         AutoSearchBar.Focus(FocusState.Programmatic);

有时 XAML Windows 10(和 8.1 RT)的行为很奇怪。引入一个小的延迟通常可以解决它。我已经尝试通过任务工厂 运行 它并且它可以在我的机器 (TM) 上运行。

private void searchButton_Click(object sender, RoutedEventArgs e)
{
    searchButton.Visibility = Visibility.Collapsed;
    AutoSearchBar.Visibility = Visibility.Visible;

    // slightly delay setting focus
    Task.Factory.StartNew(
        () => Dispatcher.RunAsync(CoreDispatcherPriority.Low,
            () => AutoSearchBar.Focus(FocusState.Programmatic)));
}