Adding a Search Results item template (Windows Store apps using C#/VB/C++ and XAML)

To enable users to search for information in your app, add a Search Results Page item to your project. Then, add SearchBox controls to any page in your app. Users search for information in your app by using these controls. To enable users to search for information in your app, perform the following steps:

  • Add the Search Results Page item.
  • Modify code in the Search Results Page item.
  • Add a SearchBox control to a page.
  • Enable users to open an item that appears in the search results.
  • Test the search feature in your app.

JJ655408.wedge(en-us,WIN.10).gifAdd the Search Results Page item

  1. On the Visual Studio menu, click File > New Project.

  2. In the left pane of the New Project dialog box, click the Visual C#, Visual Basic, or Visual C++ node.

  3. In the center pane, click Grid App.

  4. In the Name box, enter SearchPageExample, and then click the OK button.

    The solution is created and the project files appear in Solution Explorer. For more info about the project files, see C#, VB, and C++ project templates for Windows Store apps.

    Important  When you run Visual Studio for the first time, it prompts you to obtain a developer license. For more info, see Get a developer license.

  5. In Solution Explorer, open the shortcut menu of the project node, and then click Add > New Item.

  6. In the center pane of the Add New Item dialog box, click Search Results Page. For this example, keep the default name, SearchResultsPage1.xaml, that appears in the Name box.

  7. Click the Add button.

    The code for the new file is displayed

JJ655408.wedge(en-us,WIN.10).gifModify code in the Search Results Page item

  1. In the SearchResultsPage1 code file, add the following statement to the top of the file to reference the sample data classes:

    using SearchResultsExample.Data;
    
    Imports SearchResultsExample.Data
    
  2. Add the following property:

    public Dictionary<String, IEnumerable<SampleDataItem>> Results { get; set; }
    
    Public Property Results() As Dictionary(Of [String], IEnumerable(Of SampleDataItem))
        Get
            Return m_Results
        End Get
        Set(value As Dictionary(Of [String], IEnumerable(Of SampleDataItem)))
            m_Results = Value
        End Set
    End Property
    Private m_Results As Dictionary(Of [String], IEnumerable(Of SampleDataItem))
    
  3. In the navigationHelper_LoadState method, update the code after the first TODO comment by replacing

    // TODO: Application-specific searching logic.  The search process is responsible for
    //       creating a list of user-selectable result categories:
    //
    //       filterList.Add(new Filter("<filter name>", <result count>));
    //
    //       Only the first filter, typically "All", should pass true as a third argument in
    //       order to start in an active state.  Results for the active filter are provided
    //       in Filter_SelectionChanged below.
    var filterList = new List<Filter>();
    filterList.Add(new Filter("All", 0, true));
    
    ' TODO: Application-specific searching logic.  The search process is responsible for
    '       creating a list of user-selectable result categories:
    '
    '       filterList.Add(new Filter("<filter name>", <result count>));
    '
    '       Only the first filter, typically "All", should pass true as a third argument in
    '       order to start in an active state.  Results for the active filter are provided
    '       in Filter_SelectionChanged below.
    
    Dim filterList As New List(Of Filter)()
    filterList.Add(New Filter("All", 0, True))
    

    with

    var filterList = new List<Filter>();
    var totalMatchingItems = 0;
    Results = new Dictionary<string, IEnumerable<SampleDataItem>>();
    var groups = await SampleDataSource.GetGroupsAsync();
    foreach (var group in groups)
        {
            var matchingItems = group.Items.Where(item => item.Title.Contains(queryText));
            int numberOfMatchingItems = matchingItems.Count();
            if (numberOfMatchingItems > 0)
            {
                Results.Add(group.Title, matchingItems);
                filterList.Add(new Filter(group.Title, numberOfMatchingItems));
            }
            totalMatchingItems += numberOfMatchingItems;
        }
    filterList.Insert(0, new Filter("All", totalMatchingItems, true));
    
    Dim filterList = New List(Of Filter)()
    Dim totalMatchingItems = 0
    Results = New Dictionary(Of String, IEnumerable(Of SampleDataItem))()
    Dim groups As IEnumerable(Of Data.SampleDataGroup) = Await Data.SampleDataSource.GetGroupsAsync()
    For Each group In groups
        Dim matchingItems = group.Items.Where(Function(item) item.Title.Contains(queryText))
        Dim numberOfMatchingItems As Integer = matchingItems.Count()
        If numberOfMatchingItems > 0 Then
            Results.Add(group.Title, matchingItems)
            filterList.Add(New Filter(group.Title, numberOfMatchingItems))
        End If
    Next
    filterList.Insert(0, New Filter("All", totalMatchingItems, True))
    
  4. In the Filter_Checked method, update the TODO comment by replacing

    // TODO: Respond to the change in active filter by setting this.DefaultViewModel["Results"]
    //       to a collection of items with bindable Image, Title, Subtitle, and Description properties
    
    ' TODO: Respond to the change in active filter by setting Me.DefaultViewModel["Results"]
    '       to a collection of items with bindable Image, Title, Subtitle, and Description properties
    

    with

    if (selectedFilter.Name.Equals("All"))
    {
        var tempResults = new List<SampleDataItem>();
        foreach (var group in Results)   
        {
            tempResults.AddRange(group.Value);
            this.DefaultViewModel["Results"] = tempResults;
        }
    }
    else if (Results.ContainsKey(selectedFilter.Name))
    {
        this.DefaultViewModel["Results"] = 
          new List<SampleDataItem>(Results[selectedFilter.Name]);
    }
    
    If selectedFilter.Name.Equals("All") Then
    Dim tempResults = New List(Of SampleDataItem)()
    For Each group In m_Results
        tempResults.AddRange(group.Value)
        Me.DefaultViewModel("Results") = tempResults
    Next
    ElseIf m_Results.ContainsKey(selectedFilter.Name) Then
        Me.DefaultViewModel("Results") = New List(Of SampleDataItem)(m_Results(selectedFilter.Name))
    End If
    

JJ655408.wedge(en-us,WIN.10).gifAdd a SearchBox control to a page

  1. In Solution Explorer, double-click the page to which you want to add a search box (For example: GroupItemsPage.xaml).

    The page opens in the designer.

  2. From the Toolbox, drag a SearchBox control to that page.

  3. In the Properties window, click the events tab, and then in the QuerySubmitted field, type SearchBox_QuerySubmitted and press the ENTER key.

    The SearchBox_QuerySubmitted even handler opens in the code editor.

  4. Replace the SearchBox_QuerySubmitted even handler with the following code:

    private void SearchBox_QuerySubmitted(SearchBox sender, SearchBoxQuerySubmittedEventArgs args)
    {
        this.Frame.Navigate(typeof(SearchResultsPage1), args.QueryText);
    }
    
    Private Sub SearchBox_QuerySubmitted(sender As SearchBox, args As SearchBoxQuerySubmittedEventArgs)
        Me.Frame.Navigate(GetType(SearchResultsPage1), args.QueryText)
    End Sub
    

JJ655408.wedge(en-us,WIN.10).gifEnable users to open an item that appears in the search results

  1. Open SearchResultsPage1.xaml in the designer.

  2. In the Document Outline panel, click resultsGridView.

  3. In the Properties window, click the events tab, and then in the ItemClick field, type ItemClick.

  4. Add these two lines of code to the new event handler:

    private void ItemClick(object sender, ItemClickEventArgs e)
    {
        var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
        this.Frame.Navigate(typeof(ItemDetailPage), itemId);
    }
    
    Private Sub ItemClick(sender As Object, e As ItemClickEventArgs) Handles resultsGridView.ItemClick
        Dim itemId = DirectCast(e.ClickedItem, SampleDataItem).UniqueId
        Me.Frame.Navigate(GetType(ItemDetailPage), itemId)
    End Sub
    

JJ655408.wedge(en-us,WIN.10).gifTest the search feature in your app

  1. On the Visual Studio menu, click Debug > Start Debugging, or press F5.

  2. In the running app, open the page that contains your search box control.

  3. In the search box, type the name of an item, and then click the search button.

    The search results page shows results for items that include the search term.

C#, VB, and C++ item templates for Windows Store apps

Adding a Page Control item template