How can I bind and sort a collection

If I have an unsorted collection, there is an easy way to link and sort it. I would like to do this in XAML (no Linq, no C #)

If my DataContext has a property, say, MyItems, it's easy to bind it:

<ListBox ItemsSource={Binding MyItems}/> 

However, I would also like to sort it. Using CollectionViewSource should be a solution, but it does not work for me:

 <ListBox> <ListBox.ItemsSource> <Binding> <Binding.Source> <CollectionViewSource Source={Binding MyItems}/> </Binding.Source> </Binding> </ListBox.ItemsSource> </ListBox> 

At this point, my ListBox is losing its items. Am I missing something?

+4
source share
3 answers

You can define CollectionViewSource as a resource and provide the required sorting ...

 <Window.Resources> <CollectionViewSource x:Key="cvs" Source="{Binding MyItems}"> <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="MyItemName" Direction="Ascending"/> </CollectionViewSource.SortDescriptions> </CollectionViewSource> </Window.Resources> <Grid> <ListBox ItemsSource="{Binding Source={StaticResource cvs}}"/> </Grid> 

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

+9
source

Create a CollectionViewSource in a CodeBehind that reads from MyItems and bind your ListBox to this

 <ListBox ItemsSource="{Binding MyCollectionViewSource"} /> 
0
source

None of the other answers respond to sorting. They are both entitled to CollectionViewSource , but you can use this to sort using CollectionViewSource.SortDescription . Taken from here and modified:

 <Window.Resources> <src:MyItems x:Key="MyItems"/> <CollectionViewSource Source="{StaticResource MyItems}" x:Key="cvs"> <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="CityName"/> </CollectionViewSource.SortDescriptions> </CollectionViewSource> </Window.Resources> <ListBox ItemsSource="{Binding Source={StaticResource cvs}}" DisplayMemberPath="CityName" Name="lb"> <ListBox.GroupStyle> <x:Static Member="GroupStyle.Default"/> </ListBox.GroupStyle> </ListBox> 

In this example, CityName will be a property for each item in MyItems used to sort

0
source

Source: https://habr.com/ru/post/1347141/


All Articles