[Windows 8] Provide search suggestions based on local files

May 21st, 2013 | Posted by Tom in .NET | Article | Windows 8 | WinRT | Read: 2,164

Windows Store Applications allows developers to provide search suggestions to users, so they can find quickly what they are looking for.

For example, you can provide search suggestions using a Web Services or you can even use local files for that. Here is a “naïve” way to do it:

SearchPane.GetForCurrentView().SuggestionsRequested += async (sender, eventArgs) =>
{
    var deferral = eventArgs.Request.GetDeferral();

    int countNumberOfFilesAdded = 0;

    var picturesFiles = await KnownFolders.PicturesLibrary.GetFilesAsync();
    foreach (var file in picturesFiles)
    {
        if (file.DisplayName.StartsWith(eventArgs.QueryText))
        {
            eventArgs.Request.SearchSuggestionCollection.AppendQuerySuggestion(file.DisplayName);

            countNumberOfFilesAdded++;

            if (countNumberOfFilesAdded == 5)
                break;
        }
    }

    deferral.Complete();
};

The previous code woks fine and search for the files in the Pictures library to provide suggestions. But this code caan be easily replace using the LocalContentSuggestionSettings API:

var settings = new LocalContentSuggestionSettings();
settings.Enabled = true;
settings.Locations.Add(KnownFolders.PicturesLibrary);
settings.AqsFilter = "ext:jpg";

SearchPane.GetForCurrentView().SetLocalContentSuggestionSettings(settings);

Result is strictly the same: the content of the Pictures library is used to provide search suggestions:

  1. Sub-folders are include in the search
  2. You can easily customize the filter using an Advanced Query Syntax (AQS) filter
  3. You can search in all the locations you want (the Locations property is a list of StorageFolder)
  4. Code is more easier!

 

Happy coding!

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

One Response

Add Comment Register



Leave a Reply