Reputation: 6577
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?
Upvotes: 1
Views: 1174
Reputation: 2554
You can do
var sortedItems = myLookupProperty.Items.OrderBy(x => x.WhateverPropertyYouWantToSortOn);
myLookupProperty.Clear();
foreach (var item in sortedItems) {
myLookupProperty.Add(item);
}
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!
Upvotes: 1
Reputation: 19895
A CollectionView
with default sort description should work in your case. They work very well with ObservableCollection
when Add \ Remove \ Update (ofcourse INotifyPropertyChanged
based) takes place.
Upvotes: 2
Reputation: 45106
You can insert at a specific index.
public void Insert ( int index, T item )
I suspect that on start up when you build from SQL the select statement has and order by so it gets built in the proper order.
You can also use a CollectionViewSource to sort but I think it would just be easier to insert at the proper index.
Upvotes: 1