【Win10开发】关于AutoSuggestBox

时间:2023-03-10 07:27:03
【Win10开发】关于AutoSuggestBox

其实看名字我们就知道,这个控件可以提供一些建议文本。我们在做搜索框时可以做一些文本来让用户选择。

这个控件有两个关键的事件QuerySubmitted和SuggestionChosen事件,当下拉列表中的项被选择后,会发生SuggestionChosen事件。当在下拉列表中做出选择后会提交输入的文本,这时候会发生QuerySubmitted事件,从事件参数的QueryText属性可以获取输入框中要提交的查询文本。


我们做个查询单词的小例子吧,首先看看效果。

【Win10开发】关于AutoSuggestBox

那么,现在先进行xaml布局。

         <StackPanel HorizontalAlignment="Center" Width="400">
<AutoSuggestBox Name="search" QueryIcon="Find" PlaceholderText="请输入一个单词"
QuerySubmitted="search_QuerySubmitted" SuggestionChosen="search_SuggestionChosen">
</AutoSuggestBox>
<TextBlock Name="content" FontSize="40" Foreground="LightBlue"/>
</StackPanel>

接下来,我们为AutoSuggestBox控件设置下拉列表,用ItemsSource属性来指定数据源。

        string[] array = new string[]
{
"auto","suggest","search","page","surface","microsoft","keyboard","help"
};
... search.ItemsSource = array;

处理SuggestionChosen事件

         private void search_SuggestionChosen(Windows.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
{
string s = args.SelectedItem as string;
sender.Text = s;
}

处理QuerySubmitted事件

        private void search_QuerySubmitted(Windows.UI.Xaml.Controls.AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
content.Text = $"{args.QueryText}";
}

至此,这个小例子就完成了。