WPF - Combobox - Add Item when user enter text in combo
combobox, observablecollection, wpf
Solution
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;}
Problem
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> ```