How to make a WPF ComboBox editable with custom values
- by Liam
I would like to have a combobox that allows selection from a list of values and also allow a custom value from the typed in text. For display reasons the items are a complex type (lets say the combobox item template displays a patch of color and a flag indicating if it is a custom color).
public class ColorLevel
{
public decimal Intensity { get; set; }
public bool IsCustom { get; set; }
public Color BaseColor { get; set; }
public override ToString() { return string.Format("{0}", Intensity*100); }
}
Example items
var items = new [] {
new ColorLevel { Intensity = 0.9m, IsCustom = false, BaseColor = Color.Red },
new ColorLevel { Intensity = 0.7m, IsCustom = false, BaseColor = Color.Red }
}
XAML
<ComboBox SelectedItem="{Binding Path=SelectedColorLevel}"
IsEditable="true" IsTextSearchEnabled="true">
</ComboBox>
So the above markup works when an item is selected from the item list. And as you type with the text search the matching items are selected. If the typed text doesn't match an item then the SelectedColorLevel is set to null.
The question is at what point (and how) is it best to create a new custom item that can be set to the SelectedColorLevel when the typed text doesn't match an item.
For example I would want to assign a new item to the selected value such as
new ColorLevel { Intensity = decimal.Parse(textvalue), IsCustom = true }
or using an appropriate converter and databinding to the Text property.