tags:

views:

57

answers:

1

I have a ComboBox and ComboBox.IsEditable property is set to True to have a ComboBox act as both a TextBox and a drop-down list simultaneously. But when the ComboBox is data-bound, entering custom text will not cause a new item to be added to the data-bound collection.

For example, if I enter 'Joe' in a ComboBox that is bound to a list of people, which doesn't contain the value 'Joe', then the value 'Joe' is not going to be added to the drop-down list automatically.

What is the best way to handle this?

A: 

I would handle it in the LostFocus event.

Here you can check if the SelectedItem/SelectedValue is equal to the TextProperty of the ComboBox, and if not - then add it to the bound list and set the SelectedItem/SelectedValue to the new item.

In Xaml:

  <ComboBox Name="_list" LostFocus="LostFocus" IsEditable="True"/>

In code-behind:

    private ObservableCollection<string> _names;
    public MainWindow()
    {
        InitializeComponent();
        _names = new ObservableCollection<string> {"Eric", "Phillip"};
        _list.SetBinding(ItemsControl.ItemsSourceProperty, new Binding {Source = _names});
    }

    private void LostFocus(object sender, RoutedEventArgs e)
    {
        var comboBox = (ComboBox) sender;
        var name = comboBox.SelectedItem as string;
        if(comboBox.Text.Equals(name)|| string.IsNullOrEmpty(comboBox.Text))
            return;
        var newItem = comboBox.Text;
        _names.Add(newItem);
        comboBox.SelectedItem = newItem;
    }

Hope this helps :)

Goblin