【问题标题】:Sorting a listbox bound to an ObservableCollection对绑定到 ObservableCollection 的列表框进行排序
【发布时间】:2011-04-25 18:00:44
【问题描述】:

如何对我的列表框内容进行排序?在我看来,将其仅保留在 UI 层上会更有意义,因为排序不会影响我的业务逻辑,因此它可能位于 xaml 或代码隐藏中。不过我不知道该怎么做。

【问题讨论】:

    标签: wpf sorting binding observablecollection itemssource


    【解决方案1】:

    您需要为此使用CollectionView

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

    要在 XAML 中进行排序,您可以使用 CollectionViewSource 类;来自 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">
    

    【讨论】:

    • 有什么方法可以在 xaml 中代替?
    • 是的,我在回答中添加了更多信息。
    猜你喜欢
    • 1970-01-01
    • 2013-08-30
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 2019-02-28
    • 2011-05-07
    • 1970-01-01
    相关资源
    最近更新 更多