How to make a WPF ComboBox editable with custom values

Posted by Liam on Stack Overflow See other posts from Stack Overflow or by Liam
Published on 2010-02-03T06:35:53Z Indexed on 2010/06/17 2:02 UTC
Read the original article Hit count: 327

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about wpf

Related posts about databinding