介紹
重新想象 Windows 8 Store Apps 之 契約
Search Contract - 右側邊欄稱之為 Charm, 其 中的“搜索”稱之為 Search Contract
使用 Search Contract 的搜索建議,數據源在本地,以及從輸 入法編輯器中獲取相關信息
使用 Search Contract 的搜索建議,數據源在服務端,以及為搜索建議增 加圖標、描述等
使用 Search Contract 的基於本地文件的搜索建議,數據來源於文件的 metadata
示例
1、演示 Search Contract 的基本應用
Contracts/SearchContract/Demo.xaml
<Page
x:Class="XamlDemo.Contracts.SearchContract.Demo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Contracts.SearchContract"
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" Text="直接通過鍵盤輸入即可激活 SearchPane" />
<Button Name="btnShowSearch" Content="打開 SearchPane" Click="btnShowSearch_Click_1" Margin="0 10 0 0" />
</StackPanel>
</Grid>
</Page>
Contracts/SearchContract/Demo.xaml.cs
/*
* 本例演示 Search Contract 的基本應用
*
* Search Contract - 右側邊欄稱之為 Charm,其中的“搜索”稱之為 Search Contract
*
* 1、在 Package.appxmanifest 中新增一個“搜索”聲明
* 2、在 App.xaml.cs 中 override void OnSearchActivated(SearchActivatedEventArgs args),如果 app 是由搜索激活的,則可以在此獲取相關的搜索信息
*
* SearchActivatedEventArgs - 當 app 由搜索激活時的事件參數
* QueryText - 搜索文本
* PreviousExecutionState - 此 app 被搜索激活前的執行狀態(ApplicationExecutionState 枚舉:NotRunning, Running, Suspended, Terminated, ClosedByUser)
* SplashScreen - 啟動畫面對象
*
* SearchPane - 搜索面板
* GetForCurrentView() - 獲取當前的 SearchPane
* Show() - 顯示搜索面板,需要的話可以指定初始查詢字符串
* PlaceholderText - 當搜索框沒有輸入焦點且用戶未輸入任何字符時,搜索框中的提示文本
* SearchHistoryEnabled - 是否啟用搜索建議的歷史記錄功能,默認值是 true
* SearchHistoryContext - 如果啟用了搜索建議的歷史記錄功能,則此值用於指定歷史紀錄的上下文,即歷史記錄會在此上下文中保存和獲取,也就是說一個 app 的搜索建議歷史記錄可以有多套
* ShowOnKeyboardInput - 如果發現鍵盤輸入,是否激活搜索面板,默認值是 false
* Visible - 搜索面板是否是打開狀態,只讀
* QueryChanged - 搜索面板的搜索框中的文本發生變化時所觸發的事件
* QuerySubmitted - 提交搜索面板的搜索框中的文本時所觸發的事件
* VisibilityChanged - 打開或關閉搜索面板時所觸發的事件
*/
using System;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Search;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace XamlDemo.Contracts.SearchContract
{
public sealed partial class Demo : Page
{
private SearchPane _searchPane;
public Demo()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// 獲取當前的 SearchPane,並注冊相關事件
_searchPane = SearchPane.GetForCurrentView();
_searchPane.QueryChanged += _searchPane_QueryChanged;
_searchPane.QuerySubmitted += _searchPane_QuerySubmitted;
// 當搜索框沒有輸入焦點且用戶未輸入任何字符時,搜索框中的提示文本
_searchPane.PlaceholderText = "請輸入";
// 是否啟用搜索建議的歷史記錄
_searchPane.SearchHistoryEnabled = true;
// 指定搜索建議的歷史記錄的上下文
_searchPane.SearchHistoryContext = "abc";
// 如果有鍵盤輸入,則直接激活 SearchPane
_searchPane.ShowOnKeyboardInput = true;
// 通過搜索激活應用程序時(參見 App.xaml.cs 中的 OnSearchActivated() 方法)
SearchActivatedEventArgs searchActivated = (SearchActivatedEventArgs)e.Parameter;
if (searchActivated != null)
ShowSearchPane(searchActivated.QueryText);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
// 取消相關事件的監聽
_searchPane.QueryChanged -= _searchPane_QueryChanged;
_searchPane.QuerySubmitted -= _searchPane_QuerySubmitted;
_searchPane.ShowOnKeyboardInput = false;
}
private void btnShowSearch_Click_1(object sender, RoutedEventArgs e)
{
ShowSearchPane();
}
// 顯示 Search 面板
private void ShowSearchPane(string queryText="")
{
_searchPane.Show(queryText);
lblMsg.Text = queryText;
}
void _searchPane_QueryChanged(SearchPane sender, SearchPaneQueryChangedEventArgs args)
{
lblMsg.Text = args.QueryText;
}
void _searchPane_QuerySubmitted(SearchPane sender, SearchPaneQuerySubmittedEventArgs args)
{
lblMsg.Text = args.QueryText;
}
}
}
App.xaml.cs
// 通過搜索激活應用程序時所調用的方法
protected override void OnSearchActivated(SearchActivatedEventArgs args)
{
if (args.PreviousExecutionState == ApplicationExecutionState.Running)
return;
var rootFrame = new Frame();
rootFrame.Navigate(typeof(MainPage), args);
Window.Current.Content = rootFrame;
Window.Current.Activate();
}
2、本例演示如何使用 Search Contract 的搜索建議,數據源在本地。同時演示如何從輸入法編輯 器中獲取相關信息
Contracts/SearchContract/LocalSuggestion.xaml
<Page
x:Class="XamlDemo.Contracts.SearchContract.LocalSuggestion"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Contracts.SearchContract"
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" Text="本例演示如何使用 Search Contract 的搜索建議,數據源在本地。同時演示如何從輸入法編輯器中獲取相關信息" />
</StackPanel>
</Grid>
</Page>
Contracts/SearchContract/LocalSuggestion.xaml.cs
/*
* 本例演示如何使用 Search Contract 的搜索建議,數據源在本地。同時演示如何從輸入法編輯器中獲取相
關信息
*
* SearchPane - 搜索面板
* SuggestionsRequested - 用戶的查詢文本發生改變,app 需要提供新的建議時所觸發的事件(事件參數 SearchPaneSuggestionsRequestedEventArgs)
* QuerySubmitted - 提交搜索面板的搜索框中的文本時所觸發的事件
*
* SearchPaneSuggestionsRequestedEventArgs - 當需要提供新的建議時所觸發的事件
* QueryText - 搜索文本
* Request - 關於建議信息的對象,返回 SearchPaneSuggestionsRequest 類型的數據
* SearchPaneQueryLinguisticDetails - 關於輸入法編輯器信息(IME)的對象,返回 SearchPaneQueryLinguisticDetails 類型的數據
*
* SearchPaneSuggestionsRequest - 關於建議信息的對象
* SearchSuggestionCollection - 搜索面板的搜索建議集合
* Size - 搜索建議的數量,最多只支持 5 個元素,就算超過 5 個系統也只會顯示前 5 個
* AppendQuerySuggestion() & AppendQuerySuggestions() - 將指定的建議信息添加到搜索面板的建議集合中
*
* SearchPaneQueryLinguisticDetails - 關於輸入法編輯器(IME - Input Method Editor)信息的對象
* QueryTextAlternatives - 當前查詢文本 IME 中的全部可能的文本列表
* QueryTextCompositionLength - 當前在 IME 中輸入的查詢文本的長度
* QueryTextCompositionStart - 當前在 IME 中輸入的查詢文本在整個查詢字符串中的起始位置
*/
using System;
using Windows.ApplicationModel.Search;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace XamlDemo.Contracts.SearchContract
{
public sealed partial class LocalSuggestion : Page
{
private SearchPane _searchPane;
private static readonly string[] suggestionList =
{
"beijing", "北京", "beiji", "北極", "shanghai", "上海", "tianjin", "天津", "chongqing", "重慶"
};
public LocalSuggestion()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// 獲取當前的 SearchPane,並注冊相關事件
_searchPane = SearchPane.GetForCurrentView();
_searchPane.SuggestionsRequested += _searchPane_SuggestionsRequested;
_searchPane.QuerySubmitted += _searchPane_QuerySubmitted;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
// 取消相關事件的監聽
_searchPane.SuggestionsRequested -= _searchPane_SuggestionsRequested;
_searchPane.QuerySubmitted -= _searchPane_QuerySubmitted;
}
void _searchPane_SuggestionsRequested(SearchPane sender, SearchPaneSuggestionsRequestedEventArgs 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);
// 建議列表最多只支持 5 個元素,超過 5 個也只會顯示前 5 個
if (args.Request.SearchSuggestionCollection.Size >= 5)
break;
}
}
}
// 根據用戶的當前輸入,在建議列表中顯示相關建議(不考慮輸入法編輯器中的內容)
foreach (string suggestion in suggestionList)
{
if (suggestion.StartsWith(args.QueryText, StringComparison.CurrentCultureIgnoreCase))
{
args.Request.SearchSuggestionCollection.AppendQuerySuggestion(suggestion);
// 建議列表最多只支持 5 個元素,超過 5 個也只會顯示前 5 個
if (args.Request.SearchSuggestionCollection.Size >= 5)
break;
}
}
}
}
void _searchPane_QuerySubmitted(SearchPane sender, SearchPaneQuerySubmittedEventArgs args)
{
lblMsg.Text = args.QueryText;
}
}
}
3、本例演示如何使用 Search Contract 的搜索建議,數據源在服務端。同時演示如何為搜索建議 增加圖標、描述等
Contracts/SearchContract/RemoteSuggestion.xaml
<Page
x:Class="XamlDemo.Contracts.SearchContract.RemoteSuggestion"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Contracts.SearchContract"
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" Text="本例演示如何使用 Search Contract 的搜索建議,數據源在服務端。同時演示如何為搜索建議增加圖標、描述等" />
</StackPanel>
</Grid>
</Page>
Contracts/SearchContract/RemoteSuggestion.xaml.cs
/*
* 本例演示如何使用 Search Contract 的搜索建議,數據源在服務端。同時演示如何為搜索建議增加圖標、描述等
*
* SearchPane - 搜索面板
* SuggestionsRequested - 用戶的查詢文本發生改變,app 需要提供新的建議時所觸發的事件(事件參數 SearchPaneSuggestionsRequestedEventArgs)
* ResultSuggestionChosen - 提交搜索建議對象時所觸發的事件(除了查詢文本,還有圖標和描述信息的)
* 這裡所謂的搜索建議對象就是通過 AppendResultSuggestion(string text, string detailText,
string tag, IRandomAccessStreamReference image, string imageAlternateText) 構造的搜索建議
* QuerySubmitted - 提交搜索字符串時所觸發的事件(只有文本信息的)
*
* SearchPaneSuggestionsRequestedEventArgs - 當需要提供新的建議時所觸發的事件
* QueryText - 搜索文本
* Request - 關於建議信息的對象,返回 SearchPaneSuggestionsRequest 類型的數據
* SearchPaneQueryLinguisticDetails - 關於輸入法編輯器信息(IME)的對象,返回
SearchPaneQueryLinguisticDetails 類型的數據
*
* SearchPaneSuggestionsRequest - 關於建議信息的對象
* SearchSuggestionCollection - 搜索面板的搜索建議集合
* Size - 搜索建議的數量,最多只支持 5 個元素,就算超過 5 個系統也只會顯示前 5 個
* AppendQuerySuggestion() & AppendQuerySuggestions() - 將指定的建議信息添加到搜索面板的建議集合中
* AppendSearchSeparator() - 添加一個分割,可以指定分隔符左側的文本
* AppendResultSuggestion(string text, string detailText, string tag, IRandomAccessStreamReference image, string imageAlternateText) - 增加一個搜索建議對象
* text - 建議結果的文本
* detailText - 描述
* tag - 附加數據,可以在 ResultSuggestionChosen 事件的事件參數中獲取此值
* image - 圖標
* imageAlternateText - 作用未知
* GetDeferral() - 獲取異步操作對象,同時開始異步操作,之後通過 Complete() 通知完成異步操作
*/
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;
using Windows.UI.Xaml.Navigation;
namespace XamlDemo.Contracts.SearchContract
{
public sealed partial class RemoteSuggestion : Page
{
private SearchPane _searchPane;
// 用於獲取遠程建議的 HttpClient
private HttpClient _httpClient;
// 當前的 HttpClient 請求任務
private Task<string> _currentHttpTask;
public RemoteSuggestion()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// 獲取當前的 SearchPane,並注冊相關事件
_searchPane = SearchPane.GetForCurrentView();
_searchPane.SuggestionsRequested += _searchPane_SuggestionsRequested;
// 如果用戶提交的搜索數據是通過 AppendResultSuggestion(string text, string detailText, string tag, IRandomAccessStreamReference image, string imageAlternateText) 而來的,則觸發此事件
_searchPane.ResultSuggestionChosen += _searchPane_ResultSuggestionChosen;
// 如果用戶提交的搜索數據是字符串,則觸發此事件
_searchPane.QuerySubmitted += _searchPane_QuerySubmitted;
_httpClient = new HttpClient();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
// 取消相關事件的監聽
_searchPane.SuggestionsRequested -= _searchPane_SuggestionsRequested;
_searchPane.ResultSuggestionChosen -= _searchPane_ResultSuggestionChosen;
_searchPane.QuerySubmitted -= _searchPane_QuerySubmitted;
if (_httpClient != null)
{
_httpClient.Dispose();
_httpClient = null;
}
}
async void _searchPane_SuggestionsRequested(SearchPane sender, SearchPaneSuggestionsRequestedEventArgs args)
{
// 異步操作
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;
lblMsg.Text = "TaskStatus: " + task.Status.ToString();
}
finally
{
// 完成異步操作
deferral.Complete();
}
}
void _searchPane_ResultSuggestionChosen(SearchPane sender, SearchPaneResultSuggestionChosenEventArgs args)
{
lblMsg.Text = "ResultSuggestionChosen: " + args.Tag;
}
void _searchPane_QuerySubmitted(SearchPane sender, SearchPaneQuerySubmittedEventArgs args)
{
lblMsg.Text = "QuerySubmitted: " + args.QueryText;
}
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/Logo.png", UriKind.Absolute));
suggestions.AppendResultSuggestion(jv.GetArray()[0].GetString(), "detailText", jv.GetArray()[0].GetString(), imageStreamRef, "imageAlternateText");
suggestions.AppendSearchSeparator("separator");
// 建議列表最多只支持 5 個元素,超過 5 個也只會顯示前 5 個
if (suggestions.Size >= 5)
break;
}
}
}
}
4、本例演示如何使用 Search Contract 的基於本地文件的搜索建議,數據來源於文件的 metadata
Contracts/SearchContract/LocalFileSuggestion.xaml
<Page
x:Class="XamlDemo.Contracts.SearchContract.LocalFileSuggestion"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XamlDemo.Contracts.SearchContract"
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" Text="本例演示如何使用 Search Contract 的基於本地文件的搜索建議,數據來源於文件的 metadata" />
</StackPanel>
</Grid>
</Page>
Contracts/Sear0chContract/LocalFileSuggestion.xaml.cs
/*
* 本例演示如何使用 Search Contract 的基於本地文件的搜索建議,數據來源於文件的 metadata
*
* SearchPane - 搜索面板
* SetLocalContentSuggestionSettings() - 指定一個 LocalContentSuggestionSettings 對象,以實現基於本地文件的搜索建議
*
* LocalContentSuggestionSettings - 基於本地文件的搜索建議的相關配置
* Enabled - 是否啟用
* Locations - 搜索路徑
* AqsFilter - AQS 字符串,參見 http://msdn.microsoft.com/zh-cn/library/windows/apps/aa965711.aspx
* PropertiesToMatch - 用於提供搜索建議的文件屬性列表,默認會使用所有可用的文件屬性
*
*
* 注:AQS 全稱 Advanced Query Syntax
*/
using Windows.ApplicationModel.Search;
using Windows.Storage;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace XamlDemo.Contracts.SearchContract
{
public sealed partial class LocalFileSuggestion : Page
{
public LocalFileSuggestion()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// 實例化 LocalContentSuggestionSettings
var settings = new LocalContentSuggestionSettings();
settings.Enabled = true;
// 指定需要搜索的文件夾為 KnownFolders.MusicLibrary(需要在 Package.appxmanifest 的“功能”中選中“音樂庫”)
settings.Locations.Add(KnownFolders.MusicLibrary);
// 在當前的 SearchPane 中啟用指定的 LocalContentSuggestionSettings
SearchPane.GetForCurrentView().SetLocalContentSuggestionSettings(settings);
}
}
}
OK
[源碼下載]:http://files.cnblogs.com/webabcd/Windows8.rar