views:

51

answers:

2

Is there a template reverse order in Listbox? I'm using ObservableCollection and I would like to avoid any extra sorting, inserting etc.

+2  A: 

If you use Linq, you should be able to just .OrderByDescending()? Have a look at an example here - http://msdn.microsoft.com/en-us/vcsharp/aa336756.aspx

If this is for the score list you were working on from a previous question, you should be able to just order by the score amount if it's stored as an integer, without having to create a custom comparer function. An example linq query to order your list would be something like:

        var sortedItems =
            from item in myObservableCollection
            orderby item.Score descending
            select item;

Once you have the IEnumerable result of the Linq, you can recreate an ObservableCollection and reassign to your ViewModel (http://stackoverflow.com/questions/1465285/cast-linq-result-to-observablecollection)

Blakomen
thx but I use colletion of strings which is a list of the 5 latest inputs. The best fit is Queue yet it cannot be serialized and i need update the Listbox ( I can "swallow" RemoveAt(0) cuz it is only 5 elements :) ) If there is no "template-reverse-iterator" I would use what you advice
lukas
A: 

If you already have an ObservableCollection that you don't want to change I would probably go with the CollectionViewSource class. You can do it directly in XAML:

...
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
...

<UserControl.Resources>
    <CollectionViewSource x:Key="cvs" Source="{Binding}">
        <CollectionViewSource.SortDescriptions>
        <scm:SortDescription PropertyName="TheProperty" Direction="Descending" />
    </CollectionViewSource>
</UserControl.Resources>

<ListBox ItemsSource={Binding Source={StaticResource cvs}}" />
Marpe