我不确定为什么添加SortDescription
forId
不起作用,因为它应该可以正常工作。
像这样:
<CollectionViewSource x:Key="Items" Source="{Binding ElementName=UI, Path=Items}" >
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Description" />
<scm:SortDescription PropertyName="Id" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
我根据您的需要整理了一个完整的示例:
xml:
<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
Title="MainWindow" Height="124" Width="464" Name="UI" >
<Window.Resources>
<CollectionViewSource x:Key="Items" Source="{Binding ElementName=UI, Path=Items}" >
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="Description" />
<scm:SortDescription PropertyName="Id" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Source={StaticResource Items}}" />
</Grid>
代码:
public partial class MainWindow : Window
{
private ObservableCollection<MyObject> myVar = new ObservableCollection<MyObject>();
public MainWindow()
{
InitializeComponent();
Items.Add(new MyObject { Description = "Stack", Id = 5 });
Items.Add(new MyObject { Description = "OverFlow", Id = 1 });
Items.Add(new MyObject { Description = "StackOverFlow", Id = 2 });
Items.Add(new MyObject { Description = "Stack", Id = 1 });
Items.Add(new MyObject { Description = "Stack", Id = 0 });
Items.Add(new MyObject { Description = "OverFlow", Id = 7 });
}
public ObservableCollection<MyObject> Items
{
get { return myVar; }
set { myVar = value; }
}
}
public class MyObject
{
public int Id { get; set; }
public string Description { get; set; }
public override string ToString()
{
return string.Format("Desc: {0}, Id: {1}", Description, Id);
}
}
结果: