开发者

Sorting a listbox bound to an ObservableCollection

How would one go about sorting my listbox contents? It see开发者_如何学JAVAms to me that it would make more sense to keep this only on the UI layer since sorting won't affect my business logic, so it probably goes in the xaml or code-behind. I can't figure out what to do exactly though.


You will want to use a CollectionView for that.

private void Button1_Click(object sender, RoutedEventArgs e)
{
    ICollectionView view = CollectionViewSource.GetDefaultView(SomeCollection);
    view.SortDescriptions.Add
    (
        new SortDescription("Name", ListSortDirection.Descending)
    );
}

To do sorting in XAML you can use the CollectionViewSource class; Example from MSDN:

<src:Places x:Key="places"/>

<CollectionViewSource Source="{StaticResource places}" x:Key="cvs">
  <CollectionViewSource.SortDescriptions>
    <scm:SortDescription PropertyName="CityName"/>
  </CollectionViewSource.SortDescriptions>
  <CollectionViewSource.GroupDescriptions>
    <dat:PropertyGroupDescription PropertyName="State"/>
  </CollectionViewSource.GroupDescriptions>
</CollectionViewSource>

<ListBox ItemsSource="{Binding Source={StaticResource cvs}}"
         DisplayMemberPath="CityName" Name="lb">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜