WPF: Editable ComboBox Text Disappears

ComboBox looks like a simple thing, but it’s surprisingly hard to get right. Today I bumped into another bug (or feature) of the WPF combo-box. I am recording it here, so I don’t forget the details.

Suppose you have a ComboBox. The user selects an item in the combo box. ComboBox’s ItemSource then changes. If previously selected item is still in the items list, nothing happens. However, if previously selected item is not in the list, the Text property will become an empty string. This is kind of makes sense for drop-down lists, but for editable combo-boxes it looks odd.

Example:

You use a combo box to display a list of countries. You have three country lists: for Europe, Asia, Africa, and null list. Let’s say you start with Europe and the user selects Russia. Then you switch the list to Asian countries. Russia is there too, so everything’s fine. Then you switch to African countries, and voila: user selection disappears.

An unexpected feature is that if the combo-box is editable and the user types R-u-s-s-i-a instead of selecting an item from the drop-down, the text will not disappear and will remain even if you switch to an items list not containing Russia.

I wrote a little attached behavior that prevents the combo-box from losing the text when previously selected item is no longer in the list. You use it like this:

<ComboBox IsEditable="True" Text="{Binding Something}" local:ComboBoxUtils.ProtectText="True"/>

The extension source code is found here: ComboBoxUtils.cs

A complete sample program demonstrating how it works: ComboBoxText.zip

Main view: MainWindow.xaml

The view model: MainViewModel.cs

Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *