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?
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"
Create a CollectionViewSource in the CodeBehind which reads from MyItems, and bind your ListBox to that
<ListBox ItemsSource="{Binding MyCollectionViewSource"} />
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With