If none of the predefined filters suit your needs, the ItemFilter
property of the AutoCompleteBox
allows you to define a custom method for determining whether a suggestion item matches the entered text. This works well in conjunction with the MVVM pattern, as you see in this section.
To add custom filtering to an AutoCompleteBox
, you first create a method that conforms to the AutoCompleteFilterPredicate
delegate, shown here:
bool AutoCompleteFilterPredicate<T>(string search, T item)
Your custom filter method must accept a search string (the text entered by the user) and an item from the list of suggestions (usually defined by the ItemsSource
property of the AutoCompleteBox
), and it must return a Boolean value indicating whether to display the item in the suggestion list.
The sample code located in the AutoCompleteBoxViewModel
class contains a custom filter method called FilterOnLastLetter
. This custom filter method determines whether the suggestion item ends with the entered text. See the following excerpt:
static bool FilterOnLastLetter(string enteredText, object suggestionItem)
{
if (suggestionItem != null
&& suggestionItem.ToString().ToLower().EndsWith(enteredText))
{
return true;
}
return false;
}
To allow an AutoCompleteBox
to use this method, a public property called ItemFilter
is placed in the viewmodel. The FilterOnLastLetter
is declared as a static method so that it can be assigned to the itemFilter
field from outside the viewmodel’s constructor, as shown:
AutoCompleteFilterPredicate<object> itemFilter = FilterOnLastLetter;
public AutoCompleteFilterPredicate<object> ItemFilter
{
get
{
return itemFilter;
}
private set
{
Assign(ref itemFilter, value);
}
}
With the ItemFilter
property in place, the AutoCompleteBox
is able to bind to the property like so:
<toolkit:AutoCompleteBox ItemsSource="{Binding Suggestions}"
FilterMode="{Binding FilterMode, Mode=TwoWay}"
ItemFilter="{Binding ItemFilter}" />
When a user enters text into the AutoCompleteBox
, the custom filter method (FilterOnLastLetter
) is called for each item in the data bound Cities
property. Only those items ending with the entered text are displayed (see Figure 9.6).
Note
When using custom filtering, the AutoCompleteBox.FilterMode
property is automatically set to Custom.
3.143.245.137