How can I sort a ListBox using only XAML and no co

2019-01-08 12:07发布

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 instantiate the view model in XAML, as in this example, which uses the ObjectDataProvider.

In my XAML:

<ListBox ItemsSource="{Binding CollectionOfStrings}" />

In my view model:

public ObservableCollection<string> CollectionOfStrings
{
    get { return collectionOfStrings; }
}

In another component:

view.DataContext = new ViewModel();

There is no code behind! So using purely XAML, how would I sort the items in the ListBox? Again, the XAML doesn't own the instantiation of the view model.

1条回答
劳资没心,怎么记你
2楼-- · 2019-01-08 13:03

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.

查看更多
登录 后发表回答