简体   繁体   English

对数据绑定的Silverlight DataGrid进行排序

[英]Sorting a databound Silverlight DataGrid

I have a databound Silverlight DataGrid control that I am trying to sort. 我有一个要尝试排序的数据绑定Silverlight DataGrid控件。 I am using RIA services (beta) for my data source, if that makes any difference. 我正在为数据源使用RIA服务(测试版),如果有什么不同的话。

I am quite new to databinding in Silverlight, so this might be something really obvious that I've missed, but I can't seem to find any info on it. 我对Silverlight中的数据绑定非常陌生,因此我可能确实很想念它,但是我似乎找不到任何信息。 I want to be able to set the binding of the ItemSource to a collection in xaml using binding syntax, and have it sorted on one column. 我希望能够使用绑定语法将ItemSource的绑定设置为xaml中的集合,并将其排序在一个列上。

I realize I could set the ItemsSource in code and use LINQ to .OrderBy(). 我意识到我可以在代码中设置ItemsSource并使用LINQ到.OrderBy()。 But I don't get a binding that way. 但是我没有那种约束力。 It seems like there should be a simple way to do this but I can't find one. 似乎应该有一种简单的方法来执行此操作,但我找不到。 How can I keep the binding yet order my collection? 我如何保持绑定但仍订购我的收藏集?

As you are using RIA Services, you can use the DomainDataSource in your XAML. 使用RIA Services时,可以在XAML中使用DomainDataSource。 This will allow you to add SortDescriptors which will do your ordering. 这将允许您添加SortDescriptors来进行排序。 See my example below: 请参阅下面的示例:

<riaControls:DomainDataSource.SortDescriptors>
    <riaData:SortDescriptor Direction="Ascending" 
                            PropertyPath="Name" />
</riaControls:DomainDataSource.SortDescriptors>

have a look at using a CollectionViewSource. 看看如何使用CollectionViewSource。 You basically use one as a 'middleman' between your actual collection of data and you data-bound control. 基本上,您可以在实际数据收集和数据绑定控件之间使用“中间人”。

rough example: 粗略的例子:

<Window.Resources>
    <CollectionViewSource 
              Source="{Binding <<<bind to your collection here >>> }"   
              x:Key="myDataView" />

    </Window.Resources>

... ...

<ListBox Name="lsyFoo" 
    ItemsSource="{Binding Source={StaticResource myDataView}}">

... ...

then in your code behind: 然后在您的代码后面:

myDataView.SortDescriptions.Add(
                new SortDescription("<<<insert property to sort by>>>", ListSortDirection.Ascending));

(ps. you can also add grouping using PropertyGroupDescription) (ps。您还可以使用PropertyGroupDescription添加分组)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM