如何绑定和排序集合

use*_*719 5 data-binding wpf

如果我有一个未分类的集合,是否有一种简单的方法来绑定和排序它.我想在XAML中做到这一点(没有Linq,没有C#)

如果我的DataContext有一个属性,比如MyItems,很容易绑定它:

<ListBox ItemsSource={Binding MyItems}/>
Run Code Online (Sandbox Code Playgroud)

但是,我也想对它进行排序.使用CollectionViewSource应该是解决方案,但它对我不起作用:

<ListBox>
 <ListBox.ItemsSource>
  <Binding>
   <Binding.Source>
    <CollectionViewSource Source={Binding MyItems}/>
   </Binding.Source>
  </Binding>
 </ListBox.ItemsSource>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

此时,我的ListBox丢失了它的元素.我错过了一些明显的东西吗

Aar*_*ver 11

您可以将其定义CollectionViewSource为资源并提供所需的排序...

<Window.Resources>
    <CollectionViewSource x:Key="cvs" Source="{Binding MyItems}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="MyItemName" Direction="Ascending"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</Window.Resources>
<Grid>
    <ListBox ItemsSource="{Binding Source={StaticResource cvs}}"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)

scm命名空间是xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"