Welcome 2011
Basta! Samples zum Download

AutoComplete TextBox with WPF

Often I’m asked for a TextBox with automatic completion. There’s already one available with WPF. TextBox is just the wrong place to look at. It’s a ComboBox with the help of the TextSearch class. This blog entry gives you information on how this can be done.

The following ComboBox binds to  collection of the type Racer. This type contains properties Firstname and Lastname. Using the attached property TextSearch.TextPath enables auto completion. The property TextPath is set to the property of the collection that is used by search. As the user enters text in the ComboBox, the selected item moves immediately to the first matching item.

<ComboBox VerticalContentAlignment="Center" HorizontalContentAlignment="Center" TextSearch.TextPath="Firstname" Width="200" Height="100" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True"> <ComboBox.ItemTemplate> <DataTemplate> <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" > <TextBlock.Text> <MultiBinding StringFormat="{}{0} {1}"> <Binding Path="Firstname" /> <Binding Path="Lastname" /> </MultiBinding> </TextBlock.Text> </TextBlock> </DataTemplate> </ComboBox.ItemTemplate> </ComboBox>
How does this work? As the user enters text in a ComboBox, the Text property is set. With text input the protected method OnTextInput of the base class ItemsControl is invoked. This method checks for a TextSearch object and invokes the DoSearch method. So the ItemsControl and TextSearch are connected.

In case the user should be allowed to enter some data that is not in the bound list, the ComboBox property IsEditable can be set to true. Instead of using the SelectedItem in that case, the Text property of the ComboBox returns the text that is entered by the user. This sample binds to a collection of strings, setting the property TextPath to an empty string autocompletes to a string from the bound list. The user is also allowed to enter text not bound.

<ComboBox VerticalContentAlignment="Center" HorizontalContentAlignment="Center" TextSearch.TextPath="" Width="200" Height="100" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" IsEditable="True"> </ComboBox>

More information on WPF in my WPF workshop.


CN innovation


Feed You can follow this conversation by subscribing to the comment feed for this post.


As yes that is the simple solution i was looking for.

Cheers mate.

The comments to this entry are closed.