Home > Enterprise >  Sorting Datatgrid
Sorting Datatgrid

Time:09-30

I have a DataGrid in WPF app with several columns, including a Score column.I want the data to be sorted by the Score.

Is it possible sort DataGrid ?

Wpf Code:

        <DataGrid Name="datagrid_BergretterHighscore" Margin="5,5,5,5" AutoGenerateColumns="False">
            <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding Vorname}" Header="Vorname" />
                    <DataGridTextColumn Binding="{Binding Nachname}" Header="Nachname" />
                    <DataGridTextColumn Binding="{Binding Score}" Header="Score" SortDirection="Descending" />
            </DataGrid.Columns>
         
        </DataGrid>       

C# Code:

 namespace PistenDIenstListe_Views.HighscorePage
 {
    

    public partial class Highscore : Page
    {
        private static PistenDienstDB context = new PistenDienstDB();
        BergretterData bergretterData = new BergretterData(context);

        public Highscore()
        {
            InitializeComponent();

            datagrid_BergretterHighscore.ItemsSource = bergretterData.Read();
            datagrid_BergretterHighscore.IsReadOnly = true;

        }


    }
 } 

CodePudding user response:

You must use the default ICollectionView of the ItemsControl (Collection views). Since you handle the DataGrid directly, you can reference the view returned by the ItemsControl.Items property for this purpose:

public partial class Highscore : Page
{
  private static PistenDienstDB context = new PistenDienstDB();
  BergretterData bergretterData = new BergretterData(context);

  public Highscore()
  {
    InitializeComponent();

    dataGrid_BergretterHighscore.ItemsSource = bergretterData.Read();
    dataGrid_BergretterHighscore.IsReadOnly = true;

    // Sort the DataGrid programmatically
    var sortDescription = new SortDescription(nameof(MyDataObject.Score), ListSortDirection.Descending);
    dataGrid_BergretterHighscore.Items.SortDescriptions.Add(sortDescription);
  }
}
  • Related