Click here to Skip to main content
15,881,424 members
Articles / All Topics

WPF: Editable ComboBox Text Disappears

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
30 Apr 2014Apache1 min read 18.8K   433   3   1
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:

XML
<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

This article was originally posted at http://www.ikriv.com/blog?p=1413

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0


Written By
Technical Lead Thomson Reuters
United States United States
Ivan is a hands-on software architect/technical lead working for Thomson Reuters in the New York City area. At present I am mostly building complex multi-threaded WPF application for the financial sector, but I am also interested in cloud computing, web development, mobile development, etc.

Please visit my web site: www.ikriv.com.

Comments and Discussions

 
-- No messages could be retrieved (timeout) --