Sorting in window datacontext in WPF

旧街凉风 提交于 2019-12-11 09:26:28

问题


Another question related to this one.

I have a List<SortableObjects> that is the DataContext of my MainWindow. I use that list to populate a ListBox and a ComboBox. When I sort the items, both the ComboBox and the ListView get updated all right. But now I need the ComboBox to be sorted in a different way than the ListView. I. E. If the object were a Person, in the ComboBox, I'd need to sort them by LastName, but in the ListView, by birthday. How can I achieve this?

Thanks!


回答1:


Use CollectionViewSources for each of the separate orderings you want:

<UserControl.Resources>
    <CollectionViewSource x:Key="ComboBoxSource" Source="{Binding YourUnderlyingCollection}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="SomeProperty"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>

    <CollectionViewSource x:Key="ListBoxSource" Source="{Binding YourUnderlyingCollection}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="SomeOtherProperty"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</UserControl.Resources>

<ComboBox ItemsSource="{Binding Source={StaticResource ComboBoxSource}}"/>

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


来源:https://stackoverflow.com/questions/1250953/sorting-in-window-datacontext-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!