I have a WPF app that has a combobox with lookup items. The combobox is populated with a ObservableCollection property that is created in my ViewModel.
The user can popup a window to type in a new lookup value. After the user enters a new value, I write the value to the lookup table in SQL Server. This part works well.
The problem is, I then want the combobox list to be updated and sorted correctly. What is the best way to do this?
If I do this, myLookupProperty.Add(newitem), my combobox is updated but it’s not in the correct order.
If I do this, myLookupProperty = new ObservableCollection(Context.GetLookupTypes()), then the combobox is not updated until I click off the combobox and then back onto it.
Whats the best way to get newly inputted items into the table and have the combobox get these changes and have them sorted correctly?
You can do
And that will work for you. The reason that the first method you tried didn’t work (as I imagine you guessed) is that it just appends the new item to the bottom. The reason that the second method you proposed didn’t work is that you break the binding when you replace the instance of ObservableCollection that your UI has bound to. It will not properly communicate that the contents are changed after this!
As a side note, it appears that this exact question was asked here!