如何仅使用 XAML 而没有代码隐藏对 ListBox 进行排序? [英] How can I sort a ListBox using only XAML and no code-behind?

查看:27
本文介绍了如何仅使用 XAML 而没有代码隐藏对 ListBox 进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对 ListBox 中的字符串进行排序,但它通过 DataContext 由另一个组件绑定到视图模型.所以我不能直接在 XAML 中实例化视图模型,如 这个例子,它使用 ObjectDataProvider.

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.

在我的 XAML 中:

In my XAML:

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

在我的视图模型中:

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

在另一个组件中:

view.DataContext = new ViewModel();

后面没有代码!那么使用纯 XAML,我将如何对 ListBox 中的项目进行排序?同样,XAML 不拥有视图模型的实例化.

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.

推荐答案

使用 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}}"/>

您可能希望将字符串包装在自定义 VM 类中,以便您可以更轻松地应用排序行为.

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

这篇关于如何仅使用 XAML 而没有代码隐藏对 ListBox 进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆