有很多朋友从应用商店下载了应用,说怎么没有搜索功能?其实是有的,很多应用都有,人家是集成的到系统里面了。所以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、果断运行,然后回到“开始”屏幕,把鼠标移到屏幕右侧,从测边工具栏找到搜索,然后在应用列表中选择刚才写的那个应用程序,然后随便输入些内容,回车。
如果你看以上图片中的结果,那这个例子就完成了。