I have a combobox that is bound to an observablecollection of strings.
The problem is, when the string, that is actually selected in the combobox, gets changed, the combobox loses the selection.
ObservableCollection<string> myList = new ObservableCollection<string>();
myList.Add("A");
myList.Add("B");
myComboBox.ItemsSource = myList;
...
myList[0] = "C"; //<-- if selected item of combobox was myList[0], selection becomes null
I think this is, because strings are immutable and a new string-object was created.
How can I change the strings without losing the selection?
You could wrap the value of the string, but there might be better methods.
Through the implicit conversions the initial code would not even change much:
But you should set the Value property to not replace the object completely if your edit it:
Also note that using string collections for controls with selection is always problematic because if there are duplicate values the same object will be referenced and the selection will go hay-wire (much more so for ListBoxes than ComboBoxes though)