C# - WPF Reverse binded ObservableCollection in XA

2019-05-21 18:48发布

问题:

I have a ObservableCollection which is binded as ItemSource to my ComboBox. It's a ComboBox which shows you your changes which you've done. My Problem is now, that the newest Change is displayed on the bottom of the list. I tried to reverse it in the property, but when I return ComboboxName.Reverse() I get an IEnumerable back. I also don't want to make a 2nd collection with the reversed data.

An other way would be to solve this in XAML. Does someone have an idea how I can do that?

I found this answer here, but i dont get it how i can implement it. Reverse order of ObservableCollection

回答1:

scm stands for

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

There a solution that works for me. You have to adapt it to your case:

<Window.Resources>
<CollectionViewSource x:Key="customerGroups" Source="{Binding Path=Customers}">
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="IsCompany"></PropertyGroupDescription>
        </CollectionViewSource.GroupDescriptions>
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="IsCompany" Direction="Descending"/>
            <scm:SortDescription PropertyName="DisplayName" Direction="Ascending"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</Window.Resources>

Then you reference this resource as ItemsSource of your ComboBox, and bind the content to the property you need:

 <ComboBox ItemsSource="{Binding Source={StaticResource customerGroups}}">
        <DataTemplate>
            <TextBlock Text="{Binding Path= FirstName}"></TextBlock>
        </DataTemplate>
    </ComboBox>