上回寫過一個簡單的Win8 Metro風格的RSS閱讀器,詳見http://boytnt.blog.51cto.com/966121/860937,今天給它加一個搜索功能。先看圖:c#
用的是Metro App標準的搜索功能(SearchPane),按鍵盤Win+Q能夠調出來。app
上代碼,MainPage.xaml.cs:async
using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Text; using Windows.ApplicationModel.Search; //SearchPane定義在這個命名空間下 using Windows.Data.Xml.Dom; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Rss { public sealed partial class MainPage : Page { private SearchPane m_SearchPane; public MainPage() { this.InitializeComponent(); //獲取當前View的搜索面板 m_SearchPane = SearchPane.GetForCurrentView(); //提示文字,未輸入時提示用戶的 m_SearchPane.PlaceholderText = "輸入標題"; //提交時的Handler m_SearchPane.QuerySubmitted += SearchPane_QuerySubmitted; //根據用戶輸入給出建議的Handler m_SearchPane.SuggestionsRequested += SearchPane_SuggestionsRequested; } private void SearchPane_QuerySubmitted(SearchPane sender, SearchPaneQuerySubmittedEventArgs args) { var articles = gvArticles.ItemsSource as List<BlogArticle>; foreach (var article in articles) { if (article.Title == args.QueryText) { //跳轉 Redirect(article); break; } } } private void SearchPane_SuggestionsRequested(SearchPane sender, SearchPaneSuggestionsRequestedEventArgs args) { var articles = gvArticles.ItemsSource as List<BlogArticle>; foreach (var article in articles) { if (article.Title.IndexOf(args.QueryText, StringComparison.CurrentCultureIgnoreCase) >= 0) { //符合條件的加入到建議中 args.Request.SearchSuggestionCollection.AppendQuerySuggestion(article.Title); } } } protected override async void OnNavigatedTo(NavigationEventArgs e) { //內容略,見上回的代碼吧 } private void gvArticles_SelectionChanged(object sender, SelectionChangedEventArgs e) { var articles = gvArticles.ItemsSource as List<BlogArticle>; int index = gvArticles.SelectedIndex; Redirect(articles[index]); } private void Redirect(BlogArticle article) { //先去掉Handler,否則重複掛載會形成屢次響應 m_SearchPane.QuerySubmitted -= SearchPane_QuerySubmitted; m_SearchPane.SuggestionsRequested -= SearchPane_SuggestionsRequested; rootPage.Frame.Navigate(typeof(ArticlePage), article); } } }
代碼不復雜,不過想要運行,還必須聲明本程序支持搜索功能,打開Package.appxmanifest文件,添加一個針對“搜索”的聲明,如圖:
ide
另外VS版本升級了一下,彷佛變化不大哦。this