AutoSuggestBox Control In Universal Apps

An AutoSuggestBox control lets you choose items as you write on a textbox.

An AutoSuggestBox control looks like this mainly:



Here's how it is basically declared:

  1. <AutoSuggestBox Height="55" PlaceholderText="Search something..." />   
AutoSuggestBox depends on "data" and works with "fuzzy search" algorithms since you need to validate the input as text changes. 
 
I am planning to completely explain this example in 6 steps: 
  1. Project Structure
  2. UI view
  3. JSON as local data
  4. Generating your Model
  5. Building  Data Access classes
  6. Dealing with Fuzzy Search  
Project Structure

Here's how my project looks like. There's a DataSource folder to deal with json and data access. This folder includes files such as the json data and the class that does the entire job for data access and fuzzy search.



UI View

I always want to keep everything simple, so the UI should be that. Here's my XAML codes for UI of our project.
  1. <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
  2.         <AutoSuggestBox x:Name="asugbox" Height="55" Margin="234,240,212,0" TextChanged="asugbox_TextChanged" 
             Text=
    "" FontSize="32" PlaceholderText="Search a Continent..." QuerySubmitted="asugbox_QuerySubmitted" 
             SuggestionChosen=
    "asugbox_SuggestionChosen" />  
  3.         
            <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="506,131,0,0" TextWrapping="Wrap" 
             Text=
    "This isn't Google,Kid" VerticalAlignment="Top" FontSize="48"/>  
  4. </Grid>   
Using JSON as local data  

Here's how our "results.json" file look like:
  1. {  
  2.   "continents": [  
  3.     {  
  4.       "code""AF",  
  5.       "name""Africa"  
  6.     },      
  7.     {  
  8.       "code""EU",  
  9.       "name""Europe"  
  10.     },  
  11.     {  
  12.       "code""NA",  
  13.       "name""North America"  
  14.     },  
  15.     {  
  16.       "code""OC",  
  17.       "name""Oceania"  
  18.     },  
  19.     {  
  20.       "code""SA",  
  21.       "name""South America"  
  22.     }  
  23.   ]  
  24. }  
Simply it has an array named continents and continent names, codes declared as group.

Generating your Model
 
Since continent codes are not useful for me, I'll be dealing with only their names. That's why I created such a model:
  1. public class Continents  
  2. {  
  3.    public string name;  
  4.   
  5.    public override string ToString()  
  6.    {  
  7.        return string.Format("{0}", name);  
  8.    }  
  9. }  
Model property "name" will be sufficient for our example.  

Building Data Access Class 

I have named this class "SearchQueries". The main job of this class simply is parsing json, sending the values to a generic list and matching continents that does fuzzy search.

Here's the complete code for my class:
  1. public class SearchQueries    
  2. {    
  3.     List<Continents> list = new List<Continents>();    
  4.   
  5.     public List<Continents> GetResults(string query)    
  6.     {                
  7.         return list;    
  8.     }    
  9.   
  10.     public async void SetResults()    
  11.     {    
  12.         list.Clear();    
  13.         Uri dataUri = new Uri("ms-appx:///DataSource/results.json");    
  14.   
  15.         StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(dataUri);    
  16.         string jsonText = await FileIO.ReadTextAsync(file);    
  17.         JsonObject jsonObject = JsonObject.Parse(jsonText);    
  18.         JsonArray jsonArray = jsonObject["continents"].GetArray();    
  19.   
  20.         foreach (JsonValue groupValue in jsonArray)    
  21.         {    
  22.             JsonObject groupObject = groupValue.GetObject();    
  23.             list.Add(new Continents() { name= groupObject.GetNamedString("name") });                    
  24.         }    
  25.     }    
  26.   
  27.     public SearchQueries()    
  28.     {    
  29.         SetResults();    
  30.     }    
  31.   
  32.     public IEnumerable<Continents> GetMatchingContinents(string query)    
  33.     {    
  34.         return list    
  35.             .Where(c => c.name.IndexOf(query, StringComparison.CurrentCultureIgnoreCase) > -1)    
  36.             .OrderByDescending(c => c.name.StartsWith(query, StringComparison.CurrentCultureIgnoreCase));    
  37.     }    
  38. }    
Dealing with Fuzzy Search 

For this open your MainPage.xaml.cs.

We've added the following 3 events for AutoSuggestBox:
  • TextChanged event fires every time we enter something in AutoSuggestBox.
  • QuerySubmitted event fires once we submit a query.
  • SuggestionChosen event fires when the query submission ended with choosing an item and viewing it in AutoSuggestBox.
First of all create a new instance of data access class that deals with json and fuzzy search: 
  1. SearchQueries squeries = new SearchQueries();   
Next add these codes for TextChanged event:
  1. private void asugbox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)  
  2.   
  3. if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)  
  4. {  
  5.      var matchingContinents = squeries.GetMatchingContinents(sender.Text);  
  6.      sender.ItemsSource = matchingContinents.ToList();  
  7. }             
Next add these codes for QuerySubmitted event:
  1. private void asugbox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)  
  2. {  
  3.     if (args.ChosenSuggestion != null)  
  4.     {  
  5.          SelectContinent(args.ChosenSuggestion as Continents);  
  6.     }  
  7.     else  
  8.     {  
  9.          var matchingContinents = squeries.GetMatchingContinents(args.QueryText);  
  10.          if (matchingContinents.Count() >= 1)  
  11.          {  
  12.               SelectContinent(matchingContinents.FirstOrDefault());  
  13.          }  
  14.    }  
  15. }  
Next add these codes for SuggestionChosen event:  
  1. private void asugbox_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)  
  2. {  
  3.     var continents = args.SelectedItem as Continents;  
  4.     sender.Text = string.Format("{0}", continents.name);  
  5. }  
And finally add these codes for selecting the continent and writing it to the control:
  1. private void SelectContinent(Continents continents)  
  2. {  
  3.     if (continents != null)  
  4.     {  
  5.          asugbox.Text = continents.name;  
  6.     }  
  7. }  
Now run the project and see how it goes:
 

textbox

Now you can customize it as you like. I used local JSON but you can also download JSON from web and parse it.


Similar Articles