Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - Combobox - Add Item when user enter text in combo

I have a ComboBox binded with an ObservableCollection. How can I do when user enter a text in the ComboBox, if item not in the list, the code automatically add a new item to the list?

<ComboBox Name="cbTypePLC"
          Height="22" 
          ItemsSource="{StaticResource TypePLCList}"
          SelectedItem="{Binding TypePLC}" IsReadOnly="False" IsEditable="True">
</ComboBox>
like image 362
Frederic7391 Avatar asked Dec 25 '22 23:12

Frederic7391


1 Answers

Bind Text property of your combo box to your view model item and then add to the bound collection there, like,

Text="{Binding UserEnteredItem, UpdateSourceTrigger=LostFocus}"

Change the UpdateSourceTrigger to LostFocus because default (PropertyChanged) will communicate each character change to your viewmodel.

// user entered value
private string mUserEnteredItem;
public string UserEnteredItem {
    get {
        return mUserEnteredItem;
    }
    set {
        if (mUserEnteredItem != value) {
            mUserEnteredItem = value;

            TypePLCList.Add (mUserEnteredItem);

            // maybe you want to set the selected item to user entered value
            TypePLC = mUserEnteredItem;
        }
    }
}

// your selected item
private string mTypePLC;
public string TypePLC {
    get {
        return mTypePLC;
    }
    set {
        if (mTypePLC != value) {
            mTypePLC = value;

            // notify change of TypePLC INPC
        }
    }
}

// your itemsource
public ObservableCollection <string> TypePLCList { set; private set;} 
like image 161
Bhupendra Avatar answered Jan 30 '23 13:01

Bhupendra