#990 – Typing Text to Select an Item in a ListBox
January 20, 2014 Leave a comment
If a ListBox has focus, you can just type some text in order to select an item. By default, the text that you enter will be matched against the property specified by the DisplayMemberPath property, or by the value of the bound object’s ToString method, if DisplayMemberPath is not specified.
In the example below, the NameAndDates property is used as the display string. A CollectionViewSource is used to sort by last name.
<Window.Resources> <CollectionViewSource x:Key="cvsActors" Source="{Binding ActorList}"> <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="LastName" /> </CollectionViewSource.SortDescriptions> </CollectionViewSource> </Window.Resources> <StackPanel> <ListBox Name="lbActors" Margin="15,5" Width="200" Height="190" ItemsSource="{Binding Source={StaticResource cvsActors}}" DisplayMemberPath="NameAndDates" /> </StackPanel>
Once the ListBox has focus, we can type a letter to jump to the next item starting with that letter. For example, if we enter ‘J’ and then enter ‘J’ again, Joan Crawford is first selected, followed by Joan Fontaine.