AutoSuggestBox.focus 第一次不行

AutoSuggestBox.focus doesn't work first time

一个简单的东西,一个按钮,当你点击它时,它会打开一个自动提示框,让我专注于它并在移动设备上打开键盘,或者无需我自己在 "zone of text"

Boolean AutoSuggestBoxRicercaOn = true;

public MainPage()
{
    this.InitializeComponent();
    AutoSuggestion.Visibility = Visibility.Collapsed;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (AutoSuggestBoxRicercaOn)
    {
        AutoSuggestion.Visibility = Visibility.Visible;
        AutoSuggestBoxRicercaOn = false;

        AutoSuggestion.Focus(FocusState.Programmatic);
    }
    else
    {
        AutoSuggestion.Visibility = Visibility.Collapsed;
        AutoSuggestBoxRicercaOn = true;
    }
}

[xml 是一个自动提示框和一个按钮]

当我点击按钮使 ASbox 可见时,它从第二次开始起作用,而不是第一次 - 为什么?我怎样才能强制它也能够在第一次做到这一点?

感谢大家:}

It works from the second time when I click on button to make the ASbox visible, not the first - why?

如果你试图获得设置焦点方法的return结果,你会发现第一次AutoSuggestion.Focus returns false,这意味着由于某些原因,该控件不可聚焦(参见 Control class 的 Focus 方法)。这应该是第一次 AutoSuggestBox 没有聚焦的原因。

为什么控件不能聚焦,可能是AutoSuggestBox没有完成初始化,因为我加了一点Task.Delay,第一次成功。测试代码片段如下:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    if (AutoSuggestBoxRicercaOn)
    {
        AutoSuggestion.Visibility = Visibility.Visible;
        AutoSuggestBoxRicercaOn = false;
        await Task.Delay(TimeSpan.FromSeconds(0.05));
        bool setresult = AutoSuggestion.Focus(FocusState.Programmatic);
        System.Diagnostics.Debug.WriteLine("the setting focus result:" + setresult)
    }
    else
    {
        AutoSuggestion.Visibility = Visibility.Collapsed;
        AutoSuggestBoxRicercaOn = true;
    }
}

How can I force it to be able to do that on the first time too ?

您可以将初始 Visibility 属性 设置放在 Page_Loaded 事件句柄中而不是构造函数中。哪个可以取同样的效果,第一次就可以。

<Page
    ...
    mc:Ignorable="d" 
    Loaded="Page_Loaded">

private void Page_Loaded(object sender, RoutedEventArgs e)
{
    AutoSuggestion.Visibility = Visibility.Collapsed;
}