Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

WPF: Editable ComboBox Text Disappears

, 30 Apr 2014
Rate this:
Please Sign up or sign in to vote.
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

License

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

Share

About the Author

Ivan Krivyakov
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

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web04 | 2.8.140922.1 | Last Updated 30 Apr 2014
Article Copyright 2014 by Ivan Krivyakov
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid