Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 代码中的WPF datagrid火灾排序事件_C#_Wpf_Datagrid - Fatal编程技术网

C# 代码中的WPF datagrid火灾排序事件

C# 代码中的WPF datagrid火灾排序事件,c#,wpf,datagrid,C#,Wpf,Datagrid,我有一些代码可以监听datagrid的“排序”事件,以便能够添加自定义排序器 我在加载datagrid后添加这个 grid.Sorting += (sender, args) => { var column = (DataGridCustomTextColumn) args.Column; //i do some custom checking based on column to get the

我有一些代码可以监听datagrid的“排序”事件,以便能够添加自定义排序器

我在加载datagrid后添加这个

grid.Sorting += (sender, args) =>
            {
                var column = (DataGridCustomTextColumn) args.Column;



                //i do some custom checking based on column to get the right comparer
                //i have different comparers for different columns. I also handle the sort direction
                //in my comparer

                // prevent the built-in sort from sorting
                args.Handled = true;

                var direction = (column.SortDirection != ListSortDirection.Ascending)
                    ? ListSortDirection.Ascending
                    : ListSortDirection.Descending;

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

                //use a ListCollectionView to do the sort.
                var lcv = (ListCollectionView) CollectionViewSource.GetDefaultView(grid.ItemsSource);

                //this is my custom sorter it just derives from IComparer and has a few properties
                //you could just apply the comparer but i needed to do a few extra bits and pieces
                var comparer = new DataGridCommonSort(column.RealDataType, column.SortMemberPath, direction);

                //apply the sort
                lcv.CustomSort = comparer;

            };
问题是,只有在单击columnheader时才会调用此处理程序。 但是我需要一种方法来初始化触发这个事件,以便对数据进行排序

有什么想法吗? 我试过这样的方法:

ICollectionView dataView = CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);
            dataView.SortDescriptions.Clear();
            dataView.SortDescriptions.Add(new SortDescription(c.SortMemberPath, ListSortDirection.Descending));
            dataView.Refresh();

但这对我不起作用。

您可以将事件处理程序定义为(非匿名)方法:

…并在设置
ItemsSource
属性后调用它:

grid_Sorting(grid, new DataGridSortingEventArgs(grid.Columns[0])); //sort by the first column

更改DefaultView是正确的,这对我进行快速测试很有用。是否将dataGrid.ItemsSource直接设置为数据或其他collectionview?是否确定在调用GetDefaultView之前已设置?你确定c.SortMemberPath是正确的吗?
grid_Sorting(grid, new DataGridSortingEventArgs(grid.Columns[0])); //sort by the first column