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

查看:56
本文介绍了如何仅使用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中:

<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天全站免登陆