我需要一个字符串排序ListBox
,但它是由通过另一个组件绑定到视图模型DataContext
。 所以我不能直接实例在XAML视图模型,在这个例子中 ,它使用ObjectDataProvider
。
在我的XAML:
<ListBox ItemsSource="{Binding CollectionOfStrings}" />
在我的视图模型:
public ObservableCollection<string> CollectionOfStrings
{
get { return collectionOfStrings; }
}
在另一个组件:
view.DataContext = new ViewModel();
有背后没有代码! 因此,使用纯粹的XAML,我怎么会在ListBox中的项目进行排序? 同样,XAML没有自己的视图模型的实例。
使用CollectionViewSource
:
<CollectionViewSource x:Key="SortedItems" Source="{Binding CollectionOfStrings}"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="SomePropertyOnYourItems"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
<ListBox ItemsSource="{Binding Source={StaticResource SortedItems}}"/>
您可能需要您的包裹在一个自定义的虚拟机类的字符串,因此您可以更轻松地应用排序行为。