wpf 排序数据网格

uqdfh47h  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(198)

我在WPF应用程序中有一个DataGrid,它有几个列,包括一个Score列。我希望数据按Score排序。
是否可以对DataGrid进行排序?
Wpf代码:

<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#程式码:

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;

        }

    }
 }
yebdmbv4

yebdmbv41#

您必须使用ItemsControl(集合检视)的预设ICollectionView。因为您直接行程DataGrid,所以您可以参照ItemsControl.Items属性传回的检视来达到此目的:

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);
  }
}

相关问题