February 2015

Volume 30 Number 2


Modern Apps - Implement Search in Windows Store and Windows Phone Store Apps

By Rachel Appel | February 2015

Rachel AppelSearch is an integral part of our digital life. Millions of people use sites like Bing and Google to find information every day. Millions more search through the Web, apps and proprietary data stores alike. Because search is arguably the most frequently used digital feature, the smart move is to help users more easily search with your apps.

Due to the physical form factor differences of PCs, tablets and laptops, the Windows OSes provide search UIs that behave accordingly. For example, Windows Phone 8.1 uses Cortana to search (read more about Cortana at bit.ly/1nFGMxG). Apps can perform a custom search from within a Windows Phone Store app with or without Cortana. Windows Phone-based devices have a special hardware button for search, located on the bottom right of the phone itself, next to the Windows (center) and Back (left) buttons.

You can do a number of things to invoke search with Windows 8. The easiest way is to just start typing while you’re on the Windows Start screen. That kicks off the global search, across the device and the Internet. Using a swipe touch gesture is another way to invoke search for touch-enabled devices. You could also jam the mouse into the top-right or bottom-right corners of the screen to initiate search.

Finally, if you live and die by shortcut keys, you can also use Windows+S to display the Windows Search charm. Iconography doesn’t need to change due to form factors. When a user sees a magnifying glass, he knows it always means search.

Microsoft recommends using the SearchBox control, although it’s fine to use the Search charm (also called a Search Contract) for backward compatibility. You can read more about that at bit.ly/1xkqwXN. When using the SearchBox control, you can add it to your app’s canvas or show it in the app bar. If search is one of the primary methods of interacting with your app, it’s best to present it consistently throughout the app UI.

A good location is anywhere easily spotted on the app’s canvas, usually the top-right corner. Apps that deal with news, movies, sports, academic papers and financial reports are great examples of apps that need a prominent search box. Sometimes users like to browse lazily, but more often they know what they want and prefer to navigate directly to it via search.

You might be concerned with a search box taking up too much screen real estate. That’s a valid concern. Using a revealing search icon is one way to show a small but noticeable visual search indicator. After a user clicks or taps on the revealing search glyph, the SearchBox reveals itself so they can enter a search string and view results.

You can use the SearchBox to find data locally or globally. As you might expect, global searches are when your app is accessing data outside the app itself. This can be on a removable device, network or the Internet. If you do search through files such as music or pictures on the device, don’t forget to set the capabilities in the program’s manifest.

Implement Search with the SearchBox Control

You can incorporate search boxes into your apps using either XAML or HTML for Windows Store and Windows Phone Store apps. The controls and API calls conceptually work the same across languages, but naturally with different syntax. Coding search for the search charm is also roughly the same as far as complexity is concerned. The code must perform the same basic steps, and the same UX guidelines apply, regardless of language.

Figure 1 demonstrates a XAML SearchBox. You can put this control within any container control such as a StackPanel. As with other controls, you must wire up events that fire in response to the user invoking search. When you use the SearchBox control, there’s no need to set the search icon. You’ll likely want to set the FocusOnKeyboardInput to True. That lets users simply start typing to give focus control to the SearchBox, which makes for an easier search experience. 

Figure 1 The SearchBox with Suggestions Using XAML and C#

<SearchBox x:Name="SearchBox" Height="35"
  HorizontalAlignment="Stretch" VerticalAlignment="Bottom"
  SuggestionsRequested="SearchBoxEventsSuggestionsRequested"  
  QuerySubmitted="SearchBoxEventsQuerySubmitted"
  FocusOnKeyboardInput="True"/>
public sealed partial class SearchBoxWithSuggestions :
  SDKTemplate.Common.LayoutAwarePage
{
  public SearchBoxWithSuggestions()
  {
    this.InitializeComponent();
  }
  private static readonly string[] suggestionList =
  {
    "ActionScript", "Ada", "Basic", "C", "C#", "C++", "Clipper",
      "Clojure", "COBOL", "ColdFusion", "Dart", "Delphi", "Erlang",
      "F#", "Haskell", "HTML", "Java", "JavaScript", "LISP",
      "Objective-C", "Pascal", "Perl", "PowerShell", "R", "Ruby",
      "Rust", "RPG", "SQL", "SmallTalk", "Small Basic", "Swift",
      "TypeScript", "Turbo C", "Visual Basic"
  };
  private void SearchBoxEventsSuggestionsRequested(
    object sender, SearchBoxSuggestionsRequestedEventArgs e)
  {
    string queryText = e.QueryText;
    if (!string.IsNullOrEmpty(queryText))
    {
      Windows.ApplicationModel.Search.
        SearchSuggestionCollection suggestionCollection =
        e.Request.SearchSuggestionCollection;
      int n = 0;
      foreach (string suggestion in suggestionList)
      {
        if (suggestion.StartsWith(queryText,
          StringComparison.CurrentCultureIgnoreCase))
        {
          Uri uri = new Uri("ms-appx:///Assets/laptop1.png");
          RandomAccessStreamReference imageSource =
            RandomAccessStreamReference.CreateFromUri(uri);
          suggestionCollection.AppendResultSuggestion(
            suggestion, "", n.ToString(), imageSource, suggestion);
        }
      }
    }
  }
  private void SearchBoxEventsQuerySubmitted(
    object sender, SearchBoxQuerySubmittedEventArgs e)
  {
    SearchListView.Items.Add(e.QueryText);
  }
}

In XAML, the SearchBoxEventsSuggestionsRequested and SearchBoxEventsQuerySubmitted events are the two primary event wire-ups you’ll need. SearchBoxEventsSuggestionsRequested fires once for each keystroke entered to capture the keystrokes in real time. As its name suggests, SearchBoxEventsQuerySubmitted happens when the user presses Enter, clicks, taps on the search icon or otherwise triggers a search. The SearchBoxEventsQuerySubmitted event is where you add code to perform the actual search. Figure 1 shows both events in action.

In C#, the first thing you need to do is supply a list of search strings to use as suggestions. Figure 1 shows an array of strings named suggestionList. The list contains the names of several programming languages. The code in Figure 1 demonstrates a search implementation with the SearchSuggestionCollection. When the SearchBoxEventsSuggestions­Requested event fires, its argument named “e” contains the SearchSuggestionCollection to which you can append queries. That’s reflected in Figure 1 when the suggestionCollection variable is declared and set.

You can append queries to the SearchSuggestionCollection through the AppendQuerySuggestion, AppendQuerySuggestions, AppendSearchSuggestion or AppendResultSuggestion methods. Result suggestions appear in the same list as query suggestions, but they let you pass in extra data such as an image into the SearchBox.

While XAML has the notion of a Resource to set styles and aesthetic features, HTML uses CSS to perform these tasks. As an example, because the <div> element in Figure 2 contains no reference to any styles, it will use the default Windows Library for JavaScript (WinJS) .win-searchbox class that’s part of the WinJS base CSS.

Figure 2 The SearchBox with Suggestions Using HTML and JavaScript

<div id="searchBox" data-win-control="WinJS.UI.SearchBox"></div>
(function () {
"use strict";
var suggestionList = ["ActionScript", "Ada", "Basic", "C", "C#", "C++", "Clipper",
  "Clojure", "COBOL", "ColdFusion", "Dart", "Delphi", "Erlang", "F#", "Haskell",
  "HTML", "Java", "JavaScript", "LISP", "Objective-C", "Pascal", "Perl",
  "PowerShell", "R", "Ruby", "Rust", "RPG", "SQL", "SmallTalk",
  "Small Basic", "Swift", "TypeScript", "Turbo C", "Visual Basic"];
var page = WinJS.UI.Pages.define("/html/S1-SearchBoxWithSuggestions.html", {
    ready: function (element, options) {
      var searchBox = document.getElementById("searchBox");
      searchBox.addEventListener("suggestionsrequested",
        suggestionsRequestedHandler);
      searchBox.addEventListener("querysubmitted", querySubmittedHandler);
      searchBox.winControl.focusOnKeyboardInput = true;
    }
  });
function suggestionsRequestedHandler(eventObject) {
    var queryText = eventObject.detail.queryText,
      query = queryText.toLowerCase(),
      suggestionCollection = eventObject.detail.searchSuggestionCollection;
    if (queryText.length > 0) {
      for (var i = 0, len = suggestionList.length; i < len; i++) {
        if (suggestionList[i].substr(0, query.length).toLowerCase() === query) {
          suggestionCollection.appendQuerySuggestion(suggestionList[i]);
        }
      }
    }
  }
function querySubmittedHandler(eventObject) {
    var queryText = eventObject.detail.queryText;
    WinJS.log && WinJS.log(queryText, "sample", "status");
  }
})();

Figure 3 shows the runtime results of either Figure 1 or Figure 2.

Three SearchBoxes with Query and Result Suggestions
Figure 3 SearchBoxes with Query and Result Suggestions

Notice the SearchBoxes in Figure 3 show filtered suggestions based on what the user enters. This is a great feature. Fortunately, it’s something the SearchBox control does for you automatically in XAML or HTML. However, you must perform the actual search yourself in the query submission event. That means it’s up to you to read the files, access the databases and Web services, or search the Web.

When you append items to the SuggestionCollection, the AppendResultSuggestion method lets you supply more information than the AppendQuerySuggestion method. Pass in the text, description, image and alternate text to apply items in the list, as the code in Figure 4 reveals. Figure 5 illustrates the runtime screenshot the code in Figure 4 will create.

Figure 4 Code to Add Images to Suggestions

private void SearchBoxEventsSuggestionsRequested(object sender,
  SearchBoxSuggestionsRequestedEventArgs e)
{
  string queryText = e.QueryText;
  if (!string.IsNullOrEmpty(queryText))
  {
    Windows.ApplicationModel.
      Search.SearchSuggestionCollection suggestionCollection =
      e.Request.SearchSuggestionCollection;
    int n = 0;
    foreach (string suggestion in suggestionList)
    {
      if (suggestion.StartsWith(queryText,
        StringComparison.CurrentCultureIgnoreCase))
      {
        Uri uri = new Uri("ms-appx:///Assets/laptop.png");
        RandomAccessStreamReference imageSource =
          RandomAccessStreamReference.CreateFromUri(uri);
        suggestionCollection.AppendResultSuggestion(
          suggestion, "", n.ToString(), imageSource, suggestion);
      }
    }
  }

SearchBox with Result Suggestions and Images
Figure 5 SearchBox with Result Suggestions and Images

The image argument passed to the AppendResultSuggestions class is an IRandomAccessStreamReference type from the Windows.Stor­age.Streams namespace. If you’re using JavaScript, you’ll have to create a Uri using the same CreateFromUri method. This is in contrast to the usual way of setting an image in HTML with a src attribute.

At this point, you have a working SearchBox and suggestions with text and images. The next step is to display the search results. In both XAML and HTML, you can add a pre-defined search results page for displaying and interacting with the results. Visual Studio provides page templates with code that displays search results with a filtered list of data that you provide. Because these pages are customizable, you can show the results exactly how you want.

When you add a SearchResultsPage from the New File dialog in Visual Studio, it creates a page with a ListView for displaying the search results. For more information on using the ListView, see my December 2013 column, “Everything You Need to Know About the ListView Control” (msdn.microsoft.com/magazine/dn532209). Of course, it’s not mandatory you use the search results page template—you can incorporate search results anywhere into the UI that makes sense and is easiest for the user. When you do, make sure you check out the UX guidelines first.

Search UX Guidelines

If the user can never find anything, or has difficulty searching, he’ll be more apt to rate your app poorly in the store. Even worse is when a user won’t buy your app because search in the trial version doesn’t work. 

Because search is such a frequently used feature, take the time to get it right in both paid and trial apps. Here are some suggestions about how to implement search in your apps and raise those ratings:

  • If search is a frequently used feature of your app, place it where users can immediately find and use it.
  • Help users with query and result suggestions. Users rely on suggestions to quickly navigate throughout the app and perform actions.
  • Display results so they’re easy to skim. Aggregate information is the friend of both you and the user. The point of search is to present information to users so they can make a choice as to what details to pursue.
  • Ensure the search box works with a touch keyboard, as well as physical keyboards.
  • Support Ctrl+F as the keyboard shortcut for finding text in your app (Windows only).

Many of these points are aesthetic in nature. If anything, Windows UX guidelines err on the side of presenting fewer but more important pieces of information.  A user should be able to navigate back to his previous location from the search results through a back button. To catch up or refresh your knowledge on navigation in Windows Store apps, read my August 2013 column, “Navigation Essentials in Windows Store Apps” (msdn.microsoft.com/magazine/dn342878).

You should always provide search suggestions, especially on the phone. No user wants to enter a search query and receive no further help. It’s also much harder to type quickly and correctly on small devices. Phone users have fewer or restricted methods of input. Having to tap out entire words just makes your app harder to use and frustrates the user.

Searching for the Conclusion

As you can see, implementing a pleasant search experience is easy to do for Windows Store and Windows Phone Store apps. Adding search capabilities not only makes your app more robust, but it offers users easy access to an important and frequently used feature. Keep in mind you can search both global and local data.

Don’t forget to review and follow the guidelines outlined in this article and the ones Microsoft describes at bit.ly/1BQ5fGZ when implementing search in your app.


Rachel Appel is a consultant, author, mentor and former Microsoft employee with more than 20 years of experience in the IT industry. She speaks at top industry conferences such as Visual Studio Live!, DevConnections, MIX and more. Her expertise lies within developing solutions that align business and technology focusing on the Microsoft dev stack and open Web. For more about Appel, visit her Web site at rachelappel.com.

Thanks to the following Microsoft technical expert for reviewing this article: Frank La Vigne