Until now you have looked at using only predefined suggestion lists. There are times, however, when you may want to change the contents of the suggestion list based on what the user has entered. One example is performing a web search for the entered text and using the search results as the suggestion list. The user enters some text, and you call a website to get a list of suggestions. Once the call completes you populate the ItemsSource
property of the AutoCompleteBox
. This entails an asynchronous operation, which means you need some way of telling the AutoCompleteBox
to dispense with filtering until the result of the asynchronous call is obtained. Fortunately, the AutoCompleteBox
contains a built-in mechanism for doing just this. By using the AutoCompleteBox.Populating
event, you can safely coordinate the population of its suggestion list.
The following steps outline how to provide a dynamic list of suggestions as the user enters text.
1. Subscribe to the Populating
event of the AutoCompleteBox
.
2. When the event handler is called, set the Cancel
property of the PopulatingEventArgs
to true.
3. Populate the ItemsSource
property of the AutoCompleteBox
.
4. Call the PopulateComplete
method of the AutoCompleteBox
to signal that the ItemsSource
property has been populated and can be filtered.
Let’s walk through these steps. The AutoCompleteBoxView
, in the downloadable sample code, contains an event handler for the AutoCompleteBox Populating
event. When the handler is called, it cancels the event and calls the viewmodel’s Populate
method. When the viewmodel is finished retrieving the suggestions, perhaps from a web service, it calls the AutoCompleteBox.PopulateComplete
method, which is provided as an Action
parameter:
void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e)
{
e.Cancel = true;
AutoCompleteBox box = (AutoCompleteBox)sender;
ViewModel.Populate(e.Parameter, box.PopulateComplete);
}
The Populate
method is designed to show how the population of a list might take place, though it does not perform an asynchronous operation. All that is done is to replace the suggestion list with another. We could, however, be using Bing or Google, for example, to perform a search. See the following excerpt:
public void Populate(string text, Action completeAction)
{
Suggestions = new List<string>
{
"Daniel", "Sacha", "Marlon", "Pete",
"Josh", "Jaime", "Laurent", "Katka"
};
if (completeAction != null)
{
completeAction();
}
}
The specified completeAction
eventually calls the PopulateComplete
method of the AutoCompleteBox
, at which point filtering is reengaged.
Upon setting the FilterMode
of the AutoCompleteBox
to Contains and entering a single character, the suggestion list is populated as shown in Figure 9.7.
3.142.199.184