wpf 如何仅使用 XAML 而没有代码隐藏对 ListBox 进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1280704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I sort a ListBox using only XAML and no code-behind?
提问by Eben Geer
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
.
我需要对 a 中的字符串进行排序ListBox
,但它通过DataContext
. 所以我不能直接在 XAML 中实例化视图模型,就像在这个例子中一样,它使用ObjectDataProvider
.
In my XAML:
在我的 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.
后面没有代码!那么使用纯粹的 XAML,我将如何对 ListBox 中的项目进行排序?同样,XAML 不拥有视图模型的实例化。
回答by Kent Boogaart
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.
您可能希望将字符串包装在自定义 VM 类中,以便您可以更轻松地应用排序行为。