在應(yīng)用中集成搜索

2018-08-12 21:55 更新

在應(yīng)用中集成搜索

上一節(jié)是關(guān)于如何添加應(yīng)用設(shè)置和幫助,這一篇講的是和設(shè)置類似的搜索。

So…… Let's do it !

先從簡單的頁面布局開始,想想我們需要什么,一個帶搜索事件的 Button,還需要一些 TextBlock 來提示用戶,核心部分自然是一個 GridView 咯。

<Grid Background="Wheat">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition />
        </Grid.RowDefinitions>        
        <StackPanel Grid.Row="0" Orientation="Vertical">
            <Button Grid.Row="0" Name="btnSearch" VerticalAlignment="Center" HorizontalAlignment="Left" 
                Content="搜索" FontFamily="華文行楷" Click="btnSearch_Click" Margin="12" FontSize="34" Foreground="Red"/>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="搜索關(guān)鍵詞" Foreground="Green" FontSize="28" Margin="12"/>
                <TextBlock FontSize="28" Foreground="Green" Name="tBlockKeyword" Margin="12"/>
            </StackPanel>                   
        </StackPanel>
        <GridView Grid.Row="1" Margin="12" x:Name="gridView">
            <GridView.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapGrid Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </GridView.ItemsPanel>
            <GridView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" FontSize="24" Foreground="Pink" FontFamily="楷體"/>
                </DataTemplate>
            </GridView.ItemTemplate>
        </GridView>
    </Grid>

既然界面完成了,就該去后臺搗鼓咯。搜索的核心在于 SearchPane,所以先來實例化它。為了簡化,我們就將待搜索的內(nèi)容設(shè)置為一串字符串?dāng)?shù)組好了,當(dāng)然了,初始化數(shù)組的方式大家隨意就好了。

SearchPane searchPane = null;
string[] exampleStr = new string[100];
public  void InitExampleStr()
{
     Random ran = new Random();
     int exNumber;
     for(int i=0;i<100;i++)
     {
          exNumber = ran.Next(1000, 9999);
          exampleStr[i] = exNumber.ToString();                             
      }                                                                                     
}

當(dāng)用戶在搜索框中輸入的內(nèi)容發(fā)生了更改時就會觸發(fā) searchPane_QueryChange 事件。

當(dāng)用戶在完成輸入后按下 Enter 鍵或者點擊旁邊的搜索確認(rèn)按鈕后就會觸發(fā) searchPane_QuerySubmitted 事件。

        void searchPane_QueryChanged(SearchPane sender, SearchPaneQueryChangedEventArgs args)
        {                                     
            this.tBlockKeyword.Text = args.QueryText;
        }
        void searchPane_QuerySubmitted(SearchPane sender, SearchPaneQuerySubmittedEventArgs args)
        {       
            string key = args.QueryText;
            var result = exampleStr.Where(s => s.Contains(key)).ToArray();             
            this.gridView.ItemsSource = result;
        }

然后我們還需要這兩個事件在 OnNavigatedTo 中綁定以及在 OnNavigatedFrom 中解綁。

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.searchPane.QuerySubmitted += searchPane_QuerySubmitted;
            this.searchPane.QueryChanged += searchPane_QueryChanged;
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.searchPane.QuerySubmitted -= searchPane_QuerySubmitted;
            this.searchPane.QueryChanged -= searchPane_QueryChanged;
        }

然后我們需要點擊 Button 控件來調(diào)出系統(tǒng)的搜索框,一行代碼就足以搞定了。如果不想點擊按鈕也是可以得哦,可以讓用戶直接在鍵盤輸入而調(diào)出搜索框呢。

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            this.searchPane.Show();
        }
 this.searchPane.ShowOnKeyboardInput = true;

最后別忘了將他們都放到 MainPage() 中,

        public MainPage()
        {
            this.InitializeComponent();
            searchPane = SearchPane.GetForCurrentView();
            InitExampleStr();              
            this.searchPane.PlaceholderText = "請輸入關(guān)鍵字";           
            this.searchPane.ShowOnKeyboardInput = true;
        }

所以說,總的代碼是這樣的。

        SearchPane searchPane = null;
        string[] exampleStr = new string[100];
        public MainPage()
        {
            this.InitializeComponent();
            searchPane = SearchPane.GetForCurrentView();
            InitExampleStr();              
            this.searchPane.PlaceholderText = "請輸入關(guān)鍵字";           
            this.searchPane.ShowOnKeyboardInput = true;
        }
        public  void InitExampleStr()
        {
            Random ran = new Random();
            int exNumber;
            for(int i=0;i<100;i++)
            {
                exNumber = ran.Next(1000, 9999);
                exampleStr[i] = exNumber.ToString();                             
            }                                                                                     
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.searchPane.QuerySubmitted += searchPane_QuerySubmitted;
            this.searchPane.QueryChanged += searchPane_QueryChanged;
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.searchPane.QuerySubmitted -= searchPane_QuerySubmitted;
            this.searchPane.QueryChanged -= searchPane_QueryChanged;
        }
        void searchPane_QueryChanged(SearchPane sender, SearchPaneQueryChangedEventArgs args)
        {                                     
            this.tBlockKeyword.Text = args.QueryText;
        }
        void searchPane_QuerySubmitted(SearchPane sender, SearchPaneQuerySubmittedEventArgs args)
        {       
            string key = args.QueryText;
            var result = exampleStr.Where(s => s.Contains(key)).ToArray();             
            this.gridView.ItemsSource = result;
        }
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            this.searchPane.Show();
        }
    }

在清單文件中聲明你需要使用“Search”功能后就可以開始調(diào)試咯。

大家肯定都用的音樂播放器肯定都會在搜索框下面給出一些建議吧,或者大家常用的地圖等 App。

那么我們就對前面的代碼進(jìn)行更新就好。

下面這段代碼呢,就是根據(jù)用戶的輸入來顯示建議列表的方法。

void searchPane_SuggestionsRequested(SearchPane sender, SearchPaneSuggestionsRequestedEventArgs args)
  {
    var deferralSeg= args.Request.GetDeferral();
    var q = from i in exampleStr
            where i.Contains(args.QueryText)
            select i;
    var res = q.Take(suggestionLen).ToArray();
    foreach (var item in res)
      {
        args.Request.SearchSuggestionCollection.AppendQuerySuggestion(item);
      }
    deferralSeg.Complete();
  }       

這篇博客,使用大量 LINQ 技術(shù),如果不太懂的話可以看看這里。 【LINQ 技術(shù)】擴(kuò)展特性和 LINQ 操作符

使用搜索建議的最大好處在于我們可以選擇并非自己輸入的內(nèi)容,這個功能就由下面這段代碼提供動力支持。

void searchPane_ResultSuggestionChosen(SearchPane sender,  
SearchPaneResultSuggestionChosenEventArgs args)
  {                      
    sender.TrySetQueryText(args.Tag);
    var q = from t in exampleStr
            where t.Contains(args.Tag)
            select t;
   this.gridView.ItemsSource = q.ToArray();
 }

我們還可以對前面的 searchPane_QuerySubmitted 函數(shù)做如下修改。

        void searchPane_QuerySubmitted(SearchPane sender, SearchPaneQuerySubmittedEventArgs args)
        {
            //var q = from extStr in exampleStr
            //        where extStr.Contains(args.QueryText)
            //        select extStr;
            //this.gridView.ItemsSource = q.ToArray();
            string key = args.QueryText;
            var result = exampleStr.Where(s => s.Contains(key)).ToArray();
            this.gridView.ItemsSource = result;
        }

最后還需要將他們添加到 OnNavigatedTo 和 OnNavigatedFrom 方法中。

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.searchPane.QuerySubmitted += searchPane_QuerySubmitted;
            this.searchPane.QueryChanged += searchPane_QueryChanged;
            this.searchPane.SuggestionsRequested += searchPane_SuggestionsRequested;
            this.searchPane.ResultSuggestionChosen += searchPane_ResultSuggestionChosen;
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.searchPane.QuerySubmitted -= searchPane_QuerySubmitted;
            this.searchPane.QueryChanged -= searchPane_QueryChanged;
            this.searchPane.SuggestionsRequested -= searchPane_SuggestionsRequested;
            this.searchPane.ResultSuggestionChosen -= searchPane_ResultSuggestionChosen;
        }

然后調(diào)試就會是這個效果咯。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號