65.9K
CodeProject is changing. Read more.
Home

WPF: Editable ComboBox Text Disappears

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Apr 30, 2014

Apache

1 min read

viewsIcon

19081

downloadIcon

433

WPF: Editable ComboBox Text disappears

Introduction

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 combobox. 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 kind of makes sense for drop-down lists, but for editable combo-boxes, it looks odd.

Example

You use a combobox 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 can be found here: ComboBoxUtils.cs

A complete sample program demonstrating how it works can be found here: ComboBoxText.zip

Main view: MainWindow.xaml

The view model: MainViewModel.cs