有很多朋友從市集下載了應用,說怎麼沒有搜尋功能?其實是有的,很多應用都有,人家是整合的到系統裡面了。所以Win8這個搜尋功能灰常有意思,你可以在系統的搜尋窗格中選擇在任何一個地持搜尋協定的應用進行尋找,而不必要先開啟應用,再來搜尋。
我就以一個非常簡單的例子示範一下如何整合到系統的“搜尋”功能中,絕對是簡單的例子。
1、建立一個“板磚”應用程式,這個不用我說了。
2、添加一個新頁面,名字叫searchPage.xaml吧。
【註:其實在添加新項的模板已經有搜尋協定,但是那個模板會新增許多類,這就使得例子變複雜了,所以我不使用該模板。】
UI設計我們也不搞太多,一切從簡,綠色環保。
<Page x:Class="SearchApp.searchPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:SearchApp" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <StackPanel> <TextBlock FontSize="100" Text="搜尋網頁"/> <TextBlock x:Name="tbResult" FontSize="32"/> </StackPanel> </Grid></Page>
切換到程式碼檢視,我們要為searchPage類寫一個公用方法,用來接收使用者輸入的搜尋索引鍵,方法名叫SetSearchResult,先記住它,後面要用到。
public void SetSearchResult(string keywd) { this.tbResult.Text = string.Format("你輸入的關鍵詞是:{0}", keywd); }
3、為了使代碼好看,我們在一個新檔案中定義App的部分類。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;namespace SearchApp{ sealed partial class App : Application { protected override void OnSearchActivated(Windows.ApplicationModel.Activation.SearchActivatedEventArgs args) { string keyWords = args.QueryText; Frame frameRoot = Window.Current.Content as Frame; if (frameRoot == null) { frameRoot = new Frame(); Window.Current.Content = frameRoot; } frameRoot.Navigate(typeof(searchPage)); searchPage spg = frameRoot.Content as searchPage; if (spg != null) { spg.SetSearchResult(keyWords); } Window.Current.Activate(); //base.OnSearchActivated(args); } }}
從OnSearchActivated的第二個參數args的QueryText屬性我們就可以擷取使用者輸入的搜尋字串。
4、開啟資訊清單檔,切換到 聲明 選項卡,添加一個“搜尋”協定。
5、果斷運行,然後回到“開始”螢幕,把滑鼠移到螢幕右側,從測邊工具列找到搜尋,然後在應用列表中選擇剛才寫的那個應用程式,然後隨便輸入些內容,斷行符號。
如果你看以片中的結果,那這個例子就完成了。