我有一个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=""
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);
答案 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)));
}