AutoSuggestBox represents a text control that makes suggestions to users as they type. The app is notified when text has been changed by the user and is responsible for providing relevant suggestions for this control to display.
Step 1: Open a blank app and add AutoSuggestBox control either from the toolbox or by copying the following XAML code into your grid.
- <TextBlock Text="Auto Suggest Box" FontSize="20"/>
- <StackPanel>
- <StackPanel Margin="10,40,0,0" Orientation="Horizontal">
- <TextBlock Text="Auto Suggest Box" VerticalAlignment="Center"></TextBlock>
- <AutoSuggestBox Name="myAutoSuggestBox" QueryIcon="Find" PlaceholderText="search here" Margin="10,0,0,0" Width="200" TextChanged ="myAutoSuggestBox_TextChanged"></AutoSuggestBox>
- </StackPane>
- </StackPanel>
The Query Icon defines the icon to be shown in the right side of the box and PlaceholderText defines the text to be shown inside the box.
Step 2: Before running the application we have to predefine some words from which the suggestion should pop up according to the user input. For that we have to define an array of strings in the class. Here I am using the months of an year as a sample. Copy the following code to your class in cs page.
- private string[] boxitems = new string[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
Step 3: Copy and paste the following code to the myAutoSuggestBox_TextChanged event in the cs page and run your application.
- var autoSuggestBox = (AutoSuggestBox)sender;
- var filtered = boxitems.Where(p => p.StartsWith(autoSuggestBox.Text, StringComparison.OrdinalIgnoreCase)).ToArray();
- autoSuggestBox.ItemsSource = filtered;