重新想象 Windows 8.1 Store Apps (76) - 新增控件: SearchBox

时间:2023-03-08 21:59:32

[源码下载]

重新想象 Windows 8.1 Store Apps (76) - 新增控件: SearchBox

作者:webabcd

介绍
重新想象 Windows 8.1 Store Apps 之新增控件

  • SearchBox - 搜索框(数据源在本地,从输入法编辑器中获取相关信息)
  • SearchBox - 搜索框(数据源在服务端,为搜索建议增加图标、描述等)
  • SearchBox - 搜索框(数据源在本地文件的 metadata)

示例
1、SearchBox - 搜索框(本例演示数据源在本地的场景,同时演示如何从输入法编辑器中获取相关信息)
SearchBox/LocalSuggestion.xaml

<Page
x:Class="Windows81.Controls.SearchBox.LocalSuggestion"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows81.Controls.SearchBox"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="120 0 0 0"> <TextBlock Name="lblMsg" FontSize="14.667" /> <SearchBox Name="searchBox" Margin="0 0 20 0"
SuggestionsRequested="searchBox_SuggestionsRequested"
QuerySubmitted="searchBox_QuerySubmitted"
QueryChanged="searchBox_QueryChanged"
PrepareForFocusOnKeyboardInput="searchBox_PrepareForFocusOnKeyboardInput" /> </StackPanel>
</Grid>
</Page>

SearchBox/LocalSuggestion.xaml.cs

/*
* SearchBox - 搜索框(本例演示数据源在本地的场景,同时演示如何从输入法编辑器中获取相关信息)
* PlaceholderText - 当搜索框没有输入焦点且用户未输入任何字符时,搜索框中的提示文本
* SearchHistoryEnabled - 是否启用搜索建议的历史记录功能,默认值是 true
* SearchHistoryContext - 如果启用了搜索建议的历史记录功能,则此值用于指定历史纪录的上下文,即历史记录会在此上下文中保存和获取,也就是说一个 app 的搜索建议历史记录可以有多套
* FocusOnKeyboardInput - 如果发现键盘输入,是否将焦点定位到此 SearchBox,默认值是 false
* SuggestionsRequested - 用户的输入发生了改变,SearchBox 需要提供新的建议时所触发的事件(事件参数 SearchBoxSuggestionsRequestedEventArgs)
* QueryChanged - 搜索框中的文本发生变化时所触发的事件
* QuerySubmitted - 提交搜索框中的文本时所触发的事件
* PrepareForFocusOnKeyboardInput - 如果启用了 FocusOnKeyboardInput,则通过键盘激活 SearchBox 时会触发此事件
*
* SearchBoxSuggestionsRequestedEventArgs - 当需要提供新的建议时所触发的事件
* QueryText - 搜索文本
* Request - 关于建议信息的对象,返回 SearchSuggestionsRequest 类型的数据
* SearchQueryLinguisticDetails - 关于输入法编辑器信息(IME)的对象,返回 SearchQueryLinguisticDetails 类型的数据
*
* SearchSuggestionsRequest - 关于建议信息的对象
* SearchSuggestionCollection - 搜索建议集合
* Size - 搜索建议的数量
* AppendQuerySuggestion() & AppendQuerySuggestions() - 将指定的建议信息添加到搜索建议集合中
*
* SearchQueryLinguisticDetails - 关于输入法编辑器(IME - Input Method Editor)信息的对象
* QueryTextAlternatives - 当前查询文本 IME 中的全部可能的文本列表
* QueryTextCompositionLength - 当前在 IME 中输入的查询文本的长度
* QueryTextCompositionStart - 当前在 IME 中输入的查询文本在整个查询字符串中的起始位置
*
* 注:
* 1、一个应用程序不能同时使用 SearchBox 和 SearchPane
* 2、SearchBox 的使用基本同 SearchPane,关于 SearchPane 请参见:http://www.cnblogs.com/webabcd/archive/2013/07/01/3164297.html
*/ using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; namespace Windows81.Controls.SearchBox
{
public sealed partial class LocalSuggestion : Page
{
public LocalSuggestion()
{
this.InitializeComponent(); // 当搜索框没有输入焦点且用户未输入任何字符时,搜索框中的提示文本
searchBox.PlaceholderText = "请输入"; // 是否启用搜索建议的历史记录
searchBox.SearchHistoryEnabled = true;
// 指定搜索建议的历史记录的上下文
searchBox.SearchHistoryContext = "abc"; // 如果有键盘输入,则将焦点定位到指定的 SearchBox
searchBox.FocusOnKeyboardInput = true;
} private static readonly string[] suggestionList =
{
"beijing", "北京", "beiji", "北极", "shanghai", "上海", "tianjin", "天津", "chongqing", "重庆"
}; private void searchBox_SuggestionsRequested(Windows.UI.Xaml.Controls.SearchBox sender, SearchBoxSuggestionsRequestedEventArgs args)
{
if (!string.IsNullOrEmpty(args.QueryText))
{
// 根据用户当前的输入法编辑器中的内容,在建议列表中显示相关建议
foreach (string alternative in args.LinguisticDetails.QueryTextAlternatives)
{
foreach (string suggestion in suggestionList)
{
if (suggestion.StartsWith(alternative, StringComparison.CurrentCultureIgnoreCase))
{
// 将指定的建议信息添加到搜索建议集合中
args.Request.SearchSuggestionCollection.AppendQuerySuggestion(suggestion);
}
}
} // 根据用户的当前输入,在建议列表中显示相关建议(不考虑输入法编辑器中的内容)
foreach (string suggestion in suggestionList)
{
if (suggestion.StartsWith(args.QueryText, StringComparison.CurrentCultureIgnoreCase))
{
// 将指定的建议信息添加到搜索建议集合中
args.Request.SearchSuggestionCollection.AppendQuerySuggestion(suggestion);
}
}
}
} private void searchBox_QuerySubmitted(Windows.UI.Xaml.Controls.SearchBox sender, SearchBoxQuerySubmittedEventArgs args)
{
lblMsg.Text = "QuerySubmitted: " + args.QueryText;
} private void searchBox_QueryChanged(Windows.UI.Xaml.Controls.SearchBox sender, SearchBoxQueryChangedEventArgs args)
{
lblMsg.Text = "QueryChanged: " + args.QueryText;
} private void searchBox_PrepareForFocusOnKeyboardInput(Windows.UI.Xaml.Controls.SearchBox sender, RoutedEventArgs args)
{
lblMsg.Text = "PrepareForFocusOnKeyboardInput";
}
}
}

2、SearchBox - 搜索框(本例演示数据源在服务端的场景,同时演示如何为搜索建议增加图标、描述等)
SearchBox/RemoteSuggestion.xaml

<Page
x:Class="Windows81.Controls.SearchBox.RemoteSuggestion"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows81.Controls.SearchBox"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="120 0 0 0"> <TextBlock Name="lblMsg" FontSize="14.667" /> <SearchBox Name="searchBox" Margin="0 0 20 0"
SuggestionsRequested="searchBox_SuggestionsRequested"
QuerySubmitted="searchBox_QuerySubmitted"
ResultSuggestionChosen="searchBox_ResultSuggestionChosen" /> </StackPanel>
</Grid>
</Page>

SearchBox/RemoteSuggestion.xaml.cs

/*
* SearchBox - 搜索框(本例演示数据源在服务端的场景,同时演示如何为搜索建议增加图标、描述等)
* SuggestionsRequested - 用户的输入发生了改变,SearchBox 需要提供新的建议时所触发的事件(事件参数 SearchBoxSuggestionsRequestedEventArgs)
* ResultSuggestionChosen - 提交搜索建议对象时所触发的事件(除了查询文本,还有图标和描述信息的)
* 这里所谓的搜索建议对象就是通过 AppendResultSuggestion(string text, string detailText, string tag, IRandomAccessStreamReference image, string imageAlternateText) 构造的搜索建议
* QuerySubmitted - 提交搜索字符串时所触发的事件(只有文本信息的)
*
* SearchBoxSuggestionsRequestedEventArgs - 当需要提供新的建议时所触发的事件
* QueryText - 搜索文本
* Request - 关于建议信息的对象,返回 SearchSuggestionsRequest 类型的数据
* SearchQueryLinguisticDetails - 关于输入法编辑器信息(IME)的对象,返回 SearchQueryLinguisticDetails 类型的数据
*
* SearchSuggestionsRequest - 关于建议信息的对象
* SearchSuggestionCollection - 搜索建议集合
* Size - 搜索建议的数量
* AppendQuerySuggestion() & AppendQuerySuggestions() - 将指定的建议信息添加到搜索建议集合中
* AppendSearchSeparator() - 添加一个分割,可以指定分隔符左侧的文本
* AppendResultSuggestion(string text, string detailText, string tag, IRandomAccessStreamReference image, string imageAlternateText) - 增加一个搜索建议对象
* text - 建议结果的文本
* detailText - 描述
* tag - 附加数据,可以在 ResultSuggestionChosen 事件的事件参数中获取此值
* image - 图标
* imageAlternateText - 图像的替换文字
* GetDeferral() - 获取异步操作对象,同时开始异步操作,之后通过 Complete() 通知完成异步操作
*
*
* 注:
* 1、一个应用程序不能同时使用 SearchBox 和 SearchPane
* 2、SearchBox 的使用基本同 SearchPane,关于 SearchPane 请参见:http://www.cnblogs.com/webabcd/archive/2013/07/01/3164297.html
*/ using System;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.ApplicationModel.Search;
using Windows.Data.Json;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Controls; namespace Windows81.Controls.SearchBox
{
public sealed partial class RemoteSuggestion : Page
{
// 用于获取远程建议的 HttpClient
private HttpClient _httpClient;
// 当前的 HttpClient 请求任务
private Task<string> _currentHttpTask; public RemoteSuggestion()
{
this.InitializeComponent(); _httpClient = new HttpClient();
} private async void searchBox_SuggestionsRequested(Windows.UI.Xaml.Controls.SearchBox sender, SearchBoxSuggestionsRequestedEventArgs args)
{
if (!string.IsNullOrWhiteSpace(args.QueryText))
{
// 异步操作
var deferral = args.Request.GetDeferral(); try
{
Task task = GetTaobaoSuggestionsAsync("http://suggest.taobao.com/sug?extras=1&code=utf-8&q=" + args.QueryText, args.Request.SearchSuggestionCollection);
await task; if (task.Status == TaskStatus.RanToCompletion)
{
lblMsg.Text = "搜索建议的数量:" + args.Request.SearchSuggestionCollection.Size.ToString();
}
}
finally
{
// 完成异步操作
deferral.Complete();
}
}
} private void searchBox_QuerySubmitted(Windows.UI.Xaml.Controls.SearchBox sender, SearchBoxQuerySubmittedEventArgs args)
{
lblMsg.Text = "QuerySubmitted: " + args.QueryText;
} private void searchBox_ResultSuggestionChosen(Windows.UI.Xaml.Controls.SearchBox sender, SearchBoxResultSuggestionChosenEventArgs args)
{
lblMsg.Text = "ResultSuggestionChosen: " + args.Tag;
} private async Task GetTaobaoSuggestionsAsync(string str, SearchSuggestionCollection suggestions)
{
// 取消之前的 HttpClient 请求任务
if (_currentHttpTask != null)
_currentHttpTask.AsAsyncOperation<string>().Cancel(); // 新建一个 HttpClient 请求任务,以从远程获取建议列表数据
_currentHttpTask = _httpClient.GetStringAsync(str);
string response = await _currentHttpTask; // 将获取到的数据放到建议列表中
JsonObject jb = JsonObject.Parse(response);
var ary = jb["result"].GetArray();
foreach (JsonValue jv in ary)
{
// 图文方式显示建议数据
RandomAccessStreamReference imageStreamRef = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/Son.jpg", UriKind.Absolute));
suggestions.AppendResultSuggestion(jv.GetArray()[].GetString(), "detailText", jv.GetArray()[].GetString(), imageStreamRef, "imageAlternateText");
suggestions.AppendSearchSeparator("separator");
}
}
}
}

3、SearchBox - 搜索框(本例演示数据源在本地文件的 metadata 的场景)
SearchBox/LocalFileSuggestion.xaml

<Page
x:Class="Windows81.Controls.SearchBox.LocalFileSuggestion"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows81.Controls.SearchBox"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"> <Grid Background="Transparent">
<StackPanel Margin="120 0 0 0"> <TextBlock Name="lblMsg" FontSize="14.667" /> <SearchBox Name="searchBox" Margin="0 0 20 0"
QuerySubmitted="searchBox_QuerySubmitted" /> </StackPanel>
</Grid>
</Page>

SearchBox/LocalFileSuggestion.xaml.cs

/*
* SearchBox - 搜索框(本例演示数据源在本地文件的 metadata 的场景)
* SetLocalContentSuggestionSettings() - 指定一个 LocalContentSuggestionSettings 对象,以实现基于本地文件的搜索建议
*
* LocalContentSuggestionSettings - 基于本地文件的搜索建议的相关配置
* Enabled - 是否启用
* Locations - 搜索路径
* AqsFilter - AQS 字符串,参见 http://msdn.microsoft.com/zh-cn/library/windows/apps/aa965711.aspx
* PropertiesToMatch - 用于提供搜索建议的文件属性列表,默认会使用所有可用的文件属性
*
* AQS 全称 Advanced Query Syntax
*
*
* 注:
* 1、一个应用程序不能同时使用 SearchBox 和 SearchPane
* 2、SearchBox 的使用基本同 SearchPane,关于 SearchPane 请参见:http://www.cnblogs.com/webabcd/archive/2013/07/01/3164297.html
*/ using Windows.ApplicationModel.Search;
using Windows.Storage;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation; namespace Windows81.Controls.SearchBox
{
public sealed partial class LocalFileSuggestion : Page
{
public LocalFileSuggestion()
{
this.InitializeComponent();
} protected override void OnNavigatedTo(NavigationEventArgs e)
{
SetLocalContentSuggestions(true);
} protected override void OnNavigatedFrom(NavigationEventArgs e)
{
SetLocalContentSuggestions(false);
} private void SetLocalContentSuggestions(bool isLocal)
{
// 实例化 LocalContentSuggestionSettings
var settings = new LocalContentSuggestionSettings();
settings.Enabled = isLocal;
if (isLocal)
{
// 指定需要搜索的文件夹为 KnownFolders.MusicLibrary(需要在 Package.appxmanifest 的“功能”中选中“音乐库”)
settings.Locations.Add(KnownFolders.MusicLibrary);
} // 在当前的 SearchBox 中启用指定的 LocalContentSuggestionSettings
searchBox.SetLocalContentSuggestionSettings(settings);
} private void searchBox_QuerySubmitted(Windows.UI.Xaml.Controls.SearchBox sender, SearchBoxQuerySubmittedEventArgs args)
{
lblMsg.Text = "QuerySubmitted: " + args.QueryText;
}
}
}

OK
[源码下载]