WPF--implement code to control specific column sorting of DataGrid

This method works with WPF's DataGrid control.

1. Background definition method
///
/// Simulate clicking on the column header
///
/// Column name
/// Descending or ascending
private void DataGridSort(string ColumnName, ListSortDirection DescOrAsce)

    {

        ICollectionView v = CollectionViewSource.GetDefaultView(dataGrid1.ItemsSource);
        v.SortDescriptions.Clear();
        v.SortDescriptions.Add(new SortDescription(ColumnName, DescOrAsce));
        v.Refresh();
        this.dataGrid1.ColumnFromDisplayIndex(0).SortDirection = DescOrAsce;

    }

2. Call method
//button event or other events
private void button1_Click(object sender, RoutedEventArgs e)
{ //Usage DataGridSort("column binding field name", ListSortDirection.Ascending); } 3. Get the sorted result set var temp=control name.Items.Cast().Select(x => x as class name).ToList();//Sorted collection of interface fields




The program looks like this:
insert image description here
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/weixin_41883890/article/details/128955877