WPF数据网格 - 仅在命令下进行排序

3

我有自己的 DataGrid 组件(从 DataGrid 继承而来)。我希望这个组件像 MS Access 网格一样运作。我需要的是在调用方法 MySort() (MyDataGrid.MySort) 时对数据进行一次排序。

MySort 方法使用 DataGrid 的项集合,所以我向 ItemsView Sorts 添加了 SortDescription。问题是,我不希望在添加或编辑项目时重新对这个网格进行排序。排序只能由 MySort 方法调用。

如何防止 DataGridItems.SortDescription 有值时进行排序? 我需要像 do_not_resort 这样的属性。

1个回答

3
如果您使用的是.NET Framework 4或更高版本,则可以使用网格控件的“CanUserSortColumns”属性来防止自动排序。
您的自定义网格的MySort方法大致如下。
public void MySort(DataGridSortingEventArgs args)
    {
        //create a collection view for the datasource binded with grid
        ICollectionView dataView = CollectionViewSource.GetDefaultView(this.ItemsSource);
        //clear the existing sort order
        dataView.SortDescriptions.Clear();

        ListSortDirection sortDirection = args.Column.SortDirection ?? ListSortDirection.Ascending;
        //create a new sort order for the sorting that is done lastly
        dataView.SortDescriptions.Add(new SortDescription(args.Column.SortMemberPath, sortDirection));

        //refresh the view which in turn refresh the grid
        dataView.Refresh();
    }

谢谢您的快速回答,但我认为那并没有解决我的问题。那是我自己做的。 我将使用示例来展示主要问题: DataGrid显示值: 1 2 3 5 DataGrid可编辑,所以我正在将值3更改为7.....然后DataGrid重新排序(因为SortDescriptions有列名)。我不希望在添加或修改项目时自动重新排序。重新排序只能通过MySort方法完成。 - tomatino
1
CollectionViewSource会自动排序。您是否尝试过绑定通用列表而不是CollectionViewSource,因为它可以更好地控制排序?您是否按多列进行排序? - Suresh Kumar Veluswamy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接