How can I sort a ListBox using only XAML and no code-behind?

后端 未结 1 1429
囚心锁ツ
囚心锁ツ 2020-12-01 02:34

I need to sort the strings in a ListBox, but it is bound to the view model by another component via the DataContext. So I can\'t directly instantia

相关标签:
1条回答
  • 2020-12-01 03:19

    Use a CollectionViewSource:

    <CollectionViewSource x:Key="SortedItems" Source="{Binding CollectionOfStrings}"
        xmlns:scm="clr-namespace:System.ComponentModel;assembly=Win‌​dowsBase">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="SomePropertyOnYourItems"/>
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
    
    <ListBox ItemsSource="{Binding Source={StaticResource SortedItems}}"/>
    

    You might want to wrap your strings in a custom VM class so you can more easily apply sorting behavior.

    0 讨论(0)
提交回复
热议问题