You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XAML中为CollectionViewSource引用预定义SortDescriptionCollection

引用预定义的SortDescriptionCollection到CollectionViewSource

有两种实用的方式可以实现你的需求,下面分别说明细节:

方式1:直接通过属性引用资源

你已经把SortDescriptionCollection定义为可复用资源了,最简洁的方式是直接将CollectionViewSource.SortDescriptions属性绑定到这个资源上,不需要在<CollectionViewSource.SortDescriptions>标签内写额外内容:

<CollectionViewSource x:Key="csv" 
                      Source="{Binding DataContext}" 
                      SortDescriptions="{StaticResource sortDescriptors}" />

注意事项:

  • 确保你的sortDescriptors资源定义在当前CollectionViewSource可以访问到的资源字典中(比如同一个UserControl.Resources、Window.Resources或者应用级的App.xaml资源里)。
  • 如果你的资源是动态加载的,也可以用{DynamicResource sortDescriptors},但静态资源在大多数场景下更高效。

方式2:通过容器在标签内引用(不推荐,不如方式1简洁)

如果你一定要在<CollectionViewSource.SortDescriptions>标签内部处理,可以借助CollectionContainer来引用预定义集合(因为SortDescriptions是ICollection类型,支持添加容器类元素):

<CollectionViewSource x:Key="csv" Source="{Binding DataContext}">
    <CollectionViewSource.SortDescriptions>
        <CollectionContainer Collection="{StaticResource sortDescriptors}" />
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

不过这种方式多了一层容器嵌套,不如直接设置属性来得直观,所以更推荐第一种方式。

额外说明:直接在CollectionViewSource内定义预排序规则

如果你不需要复用这个SortDescriptionCollection,也可以跳过单独定义资源的步骤,直接在CollectionViewSource的SortDescriptions标签内写排序规则:

<CollectionViewSource x:Key="csv" Source="{Binding DataContext}">
    <CollectionViewSource.SortDescriptions>
        <scm:SortDescription PropertyName="Description" />
        <scm:SortDescription PropertyName="Id" />
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

这种写法适合只在当前CollectionViewSource使用的排序规则,省去了资源复用的步骤。


内容的提问来源于stack exchange,提问作者ironhide391

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:35:11