问题
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