WPF学习笔记11. Binding (4)
2010-10-11 16:33:44 来源:本站整理8. 集合视图当绑定到一个集合对象时,WPF 总是默认提供一个视图 (CollectionViewSource)。视图会关联到源集合上,并自动将相关的操作在目标对象上显示出来。
(1) 排序
向 CollectionViewSource.SortDescriptions 属性中插入一个或多个排序条件 (SortDescription) 即可实现单个或多个条件排序。
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="15" Sex="Male" /> <my:Personal Name="Mary" Age="11" Sex="Female" /> <my:Personal Name="Jack" Age="12" 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));
}
}
对 CollectionViewSource.SortDescriptions 的修改会直接反应在界面显示上。
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));
}
更多精彩
赞助商链接