This section looks at controlling an AutoCompleteBox
from a viewmodel. The example code for this section is located in the AutoCompleteBoxView
and AutoCompleteBoxViewModel
in the downloadable sample code.
AutoCompleteBox
provides various ways for selecting the items to be displayed in the suggestion list. The AutoCompleteBox.FilterMode
property allows you to specify how entered text is matched with items in the suggestion list. When a match occurs, the item is displayed in the selection list. If AutoCompleteFilterMode
is not specified, the StartsWith filter mode is used, which is not a case-sensitive filter, where the returned items start with the entered text. Table 9.1 lists the FilterMode
values.
To demonstrate the FilterMode
, we place a FilterMode
property in the viewmodel and then bind the AutoCompleteBox.FilterMode
property to it. The viewmodel’s FilterMode
property is shown in the following excerpt:
AutoCompleteFilterMode filterMode;
public AutoCompleteFilterMode FilterMode
{
get
{
return filterMode;
}
set
{
Assign(ref filterMode, value);
}
}
We bind the ItemsSource
property of the AutoCompleteBox
to the Suggestions
property of the viewmodel. A two-way data binding is used to allow the AutoCompleteBox
to update the FilterMode
when a custom filter is supplied:
<toolkit:AutoCompleteBox ItemsSource="{Binding Suggestions}"
FilterMode="{Binding FilterMode, Mode=TwoWay}" />
The viewmodel also exposes a list of available FilterModes
, as shown:
readonly List<AutoCompleteFilterMode> filterModes
= new List<AutoCompleteFilterMode>
{
AutoCompleteFilterMode.Contains,
AutoCompleteFilterMode.ContainsCaseSensitive,
/* Enum values removed for brevity. */
AutoCompleteFilterMode.StartsWithOrdinalCaseSensitive,
};
public IEnumerable<AutoCompleteFilterMode> FilterModes
{
get
{
return filterModes;
}
}
This list is used by a ListPicker
, which enables the user to select the filter mode to use. The ItemsSource
of the ListPicker
is bound to the FilterModes
property, and its SelectedItem
property uses a two-way data binding to the viewmodel’s FilterMode
property:
<toolkit:ListPicker ItemsSource="{Binding FilterModes}"
SelectedItem="{Binding FilterMode, Mode=TwoWay}" />
Selecting an alternative filter mode via the ListPicker
changes the filtering behavior of the AutoCompleteBox
(see Figure 9.5).
3.144.21.158