重新想象 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()[0].GetString(), "detailText", jv.GetArray()[0].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
[源碼下載]