Windows 8 Store Applications can take advantage of the shared “Charms” that you see when you swipe in from the right edge of your Windows 8 device (or press Win-C). The top charm is searching and it provides tremendous functionality at relatively little programming effort.
When you click search Windows 8 assumes you want to search the current application if that application has registered a Search “contract.” If it has not, Windows 8 will assume you want to search the applications, as shown in the figure (click on the figure for full size).
In any case, every program that implements a search contract will be listed and the user is free to choose a different application to search. In the image above, for example, we can see that Store, Bing, Finance, Games and so forth are all searchable.
In this first blog post on searching, we’ll build the simplest application we can to register as a Searchable application and to receive the search query. We won’t do anything with that query except display it, but this alone will demonstrate a great deal about implementing searching.
Note, this application was created by stripping down the excellent example program provided by Microsoft as part of the SDK samples.
Start by creating a new Blank App application (C# and XAML) and name it SearchDemo. The very first thing we want to do is establish that this application is a search target. To do so, double click on Package.appmanifest and click on the Declarations tab. Click on the Declarations drop down, scroll down to Search and click on it. Then click Add to add it to your declarations, as shown in the figure,
Let’s create the world’s simplest UI. Inside the grid on MainPage add this XAML:
The code behind, for now, consists of jus the single method ShowQueryText,
You will need a static reference to MainPage so create that now, and initialize it in the constructor,
Let’s turn now to App.xaml.cs,
Overwrite the method OnSearchActivated and if there is QueryText call the static Current object through MainPage (thus getting the page itself) and on that call the method ShowQueryText that we just wrote, passing in the QueryText from the SearchActivatedEventArgs,
Notice that at the top of the method we call EnsureMainPageActivatedAsync – an async method to make sure we have an active main page. Implement that as a private helper method,
This last method will ensure that if your application is called through a query and it is not running, it will open properly and behave as expected.
When you run your query now, you’ll see that this application shows in the application list and if it is the selected application the query string is displayed as shown in the figure,
Download the Application.