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

时间:2015-09-24 18:01:01

标签: c# xaml focus autosuggest windows-10-mobile

我有一个AutoSuggestBox,仅在我点击按钮时显示。当AutoSuggestBox变得可见时,它也应该得到关注。

我尝试了很多方法,但没有一种方法有效。

我的代码:

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

1 个答案:

答案 0 :(得分:7)

有时XAML for 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)));
}