Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind and sort a collection

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

If my DataContext has a property, say, MyItems, it is easy to bind against it:

<ListBox ItemsSource={Binding MyItems}/>

However, I'd like to sort it as well. Using the CollectionViewSource should be the 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 loses its elements. Am I missing something obvious?

like image 772
user380719 Avatar asked Apr 07 '11 17:04

user380719


2 Answers

You can define the CollectionViewSource as a resource and provide your desired 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>

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

like image 50
Aaron McIver Avatar answered Sep 19 '22 15:09

Aaron McIver


Create a CollectionViewSource in the CodeBehind which reads from MyItems, and bind your ListBox to that

<ListBox ItemsSource="{Binding MyCollectionViewSource"} />
like image 29
Rachel Avatar answered Sep 20 '22 15:09

Rachel