views:

21

answers:

2

I have a listbox bound to a collection. I would like the ListBox to always reverse the order of the items. This handler--hooked up to the control's load event--works for the initial load, but not thereafter. Ive tried using the SourceUpdated event but that doesnt seem to work.

How do I maintain a constant active sort?

    MyList.Items.SortDescriptions.Add(New SortDescription("Content", ListSortDirection.Descending))
A: 

If your source collection is a List<T> or some other collection that doesn't implement INotifyCollectionChanged, there is no way WPF can detect when an item is added. You need to use a collection that implements INotifyCollectionChanged, like ObservableCollection<T>.

Also, the items in your collection need to implement INotifyCollectionChanged so that changes to the items are taken into account

Thomas Levesque
A: 

How is the collection stored that supplies the items for the ListBox? It should be a collection that supports INotifyCollectionChanged. The framework provides ObservableCollection<T> which you can use.

In the constructor of your ViewModel (or wherever the collection lives), you then get the DefaultView for adding the SortDescription. The CollectionView is like a layer on top of your collection, which you can use to sort, group, filter, etc. the items without actually affecting the underlying data source. The framework creates a default one for you. To get a reference to it, you can use code similar to the following:

        var collectionView = CollectionViewSource.GetDefaultView(Widgets);
        if(collectionView == null)
            return;

        collectionView.SortDescriptions.Add(new SortDescription("Content", ListSortDirection.Descending));

With that in place, you should be able to add items to the ObservableCollection<T> and the sort order will be maintained.

Eric
I think we have a bug in our esri control. The layers collection is an ObservableCollection but it's not properly implementing INotifyCollectionChanged
Douglas
I guess you could try replacing your control with a vanilla ObservableCollection and see if the problem goes away. If so, then it looks like there could be a problem with your esri control.
Eric