3

我有一个自定义实体,其中包含 FirstName、LastName 属性(它也有其他属性)。我将此实体绑定到数据网格,它将 FullName (LastName, FirstName) 显示为 DataGridTemplateColumn(使用 MultiBinding 和 StringFormat)。允许用户对数据网格列进行排序,当他们单击 FullName 列时,记录必须按 LastName 然后 FirstName 排序(排序方向将根据点击次数切换)。我想知道在上述场景中是否可以实现所需的排序(多列)?

我尝试使用 SortMemberPath 属性,但我只能指定一列。

我知道如果我将一个名为 FullName 的自定义 ReadOnly 属性添加到我的实体中,事情会起作用,但我只想了解是否可以通过实现 MultiBinding 来实现相同的效果。

谢谢, 潘卡伊

4

1 回答 1

0

我找到了另一个有帮助的线程。您可以使用 DataGrid.Sorting 事件来覆盖此处提到的默认排序。该答案表示他或她会覆盖 DataGrid,但您不必这样做。它还假设您已使用 IList 作为数据源,因此这里有一个示例,而是假设 DataTable/DataView (IBindingList) 源:

    private void dgPeople_Sorting(object sender, DataGridSortingEventArgs e)
    {
        //Assumes you've named your column colFullName in XAML
        if (e.Column == colFullName)
        {
            ListSortDirection direction = (e.Column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending;

            //set the sort order on the column
            e.Column.SortDirection = direction;

            //Prevent the default sorting
            e.Handled = true;

            //Get the static default view that the grid is bound to to redefine its sorting
            BindingListCollectionView cv = (BindingListCollectionView)CollectionViewSource.GetDefaultView(dgPeople.ItemsSource);
            cv.SortDescriptions.Clear();
            cv.SortDescriptions.Add(new SortDescription("FirstName", direction));
            cv.SortDescriptions.Add(new SortDescription("LastName", direction));
            cv.Refresh();
        }
    }

我发现您需要对 ICollectionView(本示例中的 BindingListCollectionView)而不是 DataView 执行排序的困难方法。如果不这样做,您在 DataView 上执行的排序将被 ICollectionView 上的排序集覆盖。

我发现这个链接很有帮助:http: //msdn.microsoft.com/en-us/library/ms752347.aspx#what_are_collection_views

于 2012-05-08T20:55:42.113 回答