我如何排序只使用XAML和不隐藏代码列表框?(How can I sort a ListBox us

2019-06-18 11:16发布

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

在我的XAML:

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

在我的视图模型:

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

在另一个组件:

view.DataContext = new ViewModel();

有背后没有代码! 因此,使用纯粹的XAML,我怎么会在ListBox中的项目进行排序? 同样,XAML没有自己的视图模型的实例。

Answer 1:

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

您可能需要您的包裹在一个自定义的虚拟机类的字符串,因此您可以更轻松地应用排序行为。



文章来源: How can I sort a ListBox using only XAML and no code-behind?