AutoCompleteBox
allows you to customize the presentation of suggestion items using its ItemTemplate
property.
Sample code for this section is located in the AutoCompleteBoxTemplatedView
and AutoCompleteBoxTemplatedViewModel
.
So far a string has been used to represent suggestion items. This section uses a custom SuggestionItem
class to demonstrate more complex data binding and styling features (see Listing 9.2).
public class SuggestionItem
{
public string Name { get; private set; }
public string Description { get; private set; }
public SuggestionItem(string name, string description)
{
Name = name;
Description = description;
}
}
Within the viewmodel is defined a list of SuggestionItem
objects as shown:
IEnumerable<SuggestionItem> suggestions = new List<SuggestionItem>
{
new SuggestionItem("Prague", "Capital of the Czech Republic."),
new SuggestionItem("Geneva", "Swiss city."),
new SuggestionItem("Canberra", "Capital of Australia."),
...
};
To have the AutoCompleteBox
function correctly with a complex object, such as the custom SuggestionItem
class, you need to inform it of which property to use for filtering. This is done using the AutoCompleteBox.ValueMemberPath
property. The following excerpt shows how the Name
property of the SuggestionItem
class is designated as the filter property. You also see how a DataTemplate
is used to present the Name
and Description
of each SuggestionItem
object:
<toolkit:AutoCompleteBox
ItemsSource="{Binding Suggestions}"
ValueMemberPath="Name"
FontFamily="{StaticResource PhoneFontFamilySemiBold}"
FontSize="{StaticResource PhoneFontSizeSmall}"
VerticalAlignment="Top">
<toolkit:AutoCompleteBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"
FontSize="{StaticResource PhoneFontSizeNormal}" />
<TextBlock Text="{Binding Description}"
FontSize="{StaticResource PhoneFontSizeSmall}"
Foreground="#ff666666" />
</StackPanel>
</DataTemplate>
</toolkit:AutoCompleteBox.ItemTemplate>
</toolkit:AutoCompleteBox>
When the suggestion list is displayed, each SuggestionItem
is presented using the DataTemplate
, as shown in Figure 9.8.
Tip
If you want to programmatically collapse the suggestion list, set the AutoCompleteBox.IsDropDownOpen
property to false.
3.137.217.17