【问题标题】:Sort a wpf datagrid programmatically以编程方式对 wpf 数据网格进行排序
【发布时间】:2013-06-02 02:48:08
【问题描述】:

有没有办法以编程方式对 WPF DataGrid 进行排序(例如,如果我单击了第一列)?

有没有办法模拟这种点击?

这是我的代码:

Collection_Evenements = new ObservableCollection<Evenement>();
 
Collection_Evenements = myEvenement.GetEvenementsForCliCode(App.obj_myClient.m_strCode);
Collection_Evenements.CollectionChanged += Collection_Evenements_CollectionChanged;
myDataGridEvenements.ItemsSource = Collection_Evenements;
 
System.Data.DataView dv = (System.Data.DataView)myDataGridEvenements.ItemsSource;
dv.Sort = "strEvtType";
            
myDataGridEvenements.Focus();
myDataGridEvenements.SelectedIndex = 0;
myDataGridEvenements.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

我不知道为什么,但是dv.Sort = "strEvtType"; 行导致了一个奇怪的事情,我的窗口出现了,程序没有继续执行下一行,但是,我没有看到排序!

【问题讨论】:

  • 不能对 DataGrid 视图进行排序吗?并刷新布局?
  • 你有例子吗?这是怎么做的?谢谢

标签: c# .net wpf xaml datagrid


【解决方案1】:

voo 的解决方案对我不起作用,ItemsSource 为空,很可能是因为它不是直接设置的,而是绑定的。 我在 StackOverflow 找到的所有其他解决方案都只处理模型排序,但 DataGrid 标头没有反映到排序。

这里有一个基于不完整脚本的正确解决方案:http://dotnetgui.blogspot.co.uk/2011/02/how-to-properly-sort-on-wpf-datagrid.html

public static void SortDataGrid(DataGrid dataGrid, int columnIndex = 0, ListSortDirection sortDirection = ListSortDirection.Ascending)
{
    var column = dataGrid.Columns[columnIndex];

    // Clear current sort descriptions
    dataGrid.Items.SortDescriptions.Clear();

    // Add the new sort description
    dataGrid.Items.SortDescriptions.Add(new SortDescription(column.SortMemberPath, sortDirection));

    // Apply sort
    foreach (var col in dataGrid.Columns)
    {
        col.SortDirection = null;
    }
    column.SortDirection = sortDirection;

    // Refresh items to display sort
    dataGrid.Items.Refresh();
}

如果是你的代码,可以这样使用:

SortDataGrid(myDataGridEvenements, 0, ListSortDirection.Ascending);

或者通过使用默认参数值,简单地说:

SortDataGrid(myDataGridEvenements);

【讨论】:

  • 很棒的方法,易于使用和修改。谢谢。
  • 这确实显示了软箭头,但仅此而已。排序实际上并未执行。
【解决方案2】:

获取您的 ItemsSource 的 DataView 并使用它的 Sort 属性来指定您要排序的列:

(yourDataGrid.ItemsSource as DataView).Sort = "NAME_OF_COLUMN";

【讨论】:

  • 您好,感谢您的回答。列的名称是什么,是“标题”属性?我没有找到名称属性:(
  • @WalterFabioSimoni 不,它是绑定到 DataGrid 的源列的名称。
  • 好的,明白了!尽管如此,当程序进入 .Sort 行时,我的程序窗口会显示出来,仅此而已!很奇怪
  • @WalterFabioSimoni 您的 Evenement 类型的结构是什么?我想你应该传递你想要排序的 Evenement 的属性名称。
  • 设置排序值实际上并不对数据进行排序。
【解决方案3】:

快速简便的方法:

dgv.Items.SortDescriptions.Clear();
dgv.Items.SortDescriptions.Add(new SortDescription("ID", ListSortDirection.Descending));
dgv.Items.Refresh();

【讨论】:

    【解决方案4】:

    我的方法对我有用。 试试这个代码。对不起俄语

    // Если таблица пустая, то привязываем ее к журналу 
                if(dgEvents.ItemsSource == null)
                    dgEvents.ItemsSource = events.Entries;
                // Обновляем записи
                CollectionViewSource.GetDefaultView(dgEvents.ItemsSource).Refresh();
                // Очищаем описание сортировки
                dgEvents.Items.SortDescriptions.Clear();
                // Созадем описание сортировки
                dgEvents.Items.SortDescriptions.Add(new SortDescription(dgEvents.Columns[0].SortMemberPath, ListSortDirection.Descending));
    
                // Очищаем сортировку всех столбцов
                foreach (var col in dgEvents.Columns)
                {
                    col.SortDirection = null;
                }
                // Задаем сортировку времени по убыванию (последняя запись вверху)
                dgEvents.Columns[0].SortDirection = ListSortDirection.Descending;
                // Обновляем записи
                dgEvents.Items.Refresh();
    

    【讨论】:

      【解决方案5】:

      PerformSort DataGrid 的方法是在单击列标题时实际执行的。然而,这种方法是内部的。所以如果你真的想模拟点击你需要使用反射:

      public static void SortColumn(DataGrid dataGrid, int columnIndex)
      {
          var performSortMethod = typeof(DataGrid)
                                  .GetMethod("PerformSort",
                                             BindingFlags.Instance | BindingFlags.NonPublic);
      
          performSortMethod?.Invoke(dataGrid, new[] { dataGrid.Columns[columnIndex] });
      }
      

      【讨论】:

      • 像魅力一样工作,ty :D
      【解决方案6】:

      您可以使用ICollectionView 在数据网格中过滤、排序和分组您的项目。

      编辑:添加排序,没有仔细阅读问题:)

       var view = CollectionViewSource.GetDefaultView(this.MyData);
       view.Filter = ViewFilter;
       view.SortDescriptions.Add(new SortDescription("MyPropertyToSort", ListSortDirection.Descending));
      
      
          private bool ViewFilter(object obj)
          {
              var item = obj as MyObject;
      
              if (item == null)
                  return false;
      
              //your filter logik goes here
      
              if(item.MyStringProp.StartsWith("Test"))
                  return false;
      
              return true;
      
      
         }
      

      【讨论】:

      猜你喜欢
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多