8. Collection view when binding to a collection object, WPF always provides a view by default (CollectionViewSource). The view is associated to the source collection and automatically displays the associated action on the target object.
(1) Sorting
Inserting one or more sort criteria (sortdescription) into the Collectionviewsource.sortdescriptions property enables single or multiple conditional sorting.
Window1.xaml
<window x:class= "Learn.WPF.Window1"
Xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"
Xmlns:my= "CLR-NAMESPACE:LEARN.WPF"
title= "Window1" >
<Window.Resources>
<my:personallist x:key= "Personals" >
<my:personal name= "Tom" age= "sex=" Male "/>"
<my:personal name= "Mary" age= "one" sex= "Female"/>
<my:personal name= "Jack" age= "sex=" Male "/>"
</my:PersonalList>
</Window.Resources>
<Grid>
<stackpanel datacontext= "{StaticResource personals}" >
<listbox x:name= "ListBox1" Itemssource= "{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<stackpanel orientation= "Horizontal" >
<textblock text= "{Binding path=name}"/>
<TextBlock>,</TextBlock>
<textblock text= "{Binding path=age}"/>
<TextBlock>,</TextBlock>
<textblock text= "{Binding path=sex}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
</Window>
Window1.xaml.cs
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
var personals = this.FindResource("personals");
var view = CollectionViewSource.GetDefaultView(personals);
view.SortDescriptions.Add(new SortDescription("Age", ListSortDirection.Ascending));
}
}
Changes to the collectionviewsource.sortdescriptions will be directly reflected in the interface display.
protected void ButtonClick(object sender, RoutedEventArgs e)
{
var personals = this.FindResource("personals");
var view = CollectionViewSource.GetDefaultView(personals);
var direction = sender == btnDesc ? ListSortDirection.Descending : ListSortDirection.Ascending;
view.SortDescriptions.Clear();
view.SortDescriptions.Add(new SortDescription("Age", direction));
}