2013-06-06 61 views
17

有沒有辦法對WPF DataGrid程序進行排序(例如,如果我點擊了我的第一列)。以編程方式對wpf數據網格進行排序

有沒有一種方法來模擬此點擊?還是最好的方法?

這裏是我的代碼:

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「;」導致一個奇怪的事情,我的窗口顯示和程序不會繼續執行下一行,但我看不到這種!

非常感謝,

最好的問候,

Nixeus

+0

你不能排序的DataGrid的看法?並刷新佈局? – Alex

+1

請問您有個例子嗎?如何做到這一點?謝謝 –

回答

7

讓您的ItemsSource的數據視圖,並利用其排序屬性來指定要通過排序列:

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

你好,謝謝你的回答。列的名稱是什麼,是「標題」屬性?我沒有找到名稱屬性:( –

+0

@WalterFabioSimoni不,它是你的源的列的名稱,你綁定到你的DataGrid。 – Alex

+0

好吧,理解!然而,當程序繼續.Sort行,我的程序窗口顯示和這是所有!這很奇怪 –

0

你可以使用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; 


    } 
+0

如果您不綁定到對象集合,而是綁定到數據表 - 您必須使用IBindingListView.Filter(http://msdn.microsoft.com/de-de/library/system.componentmodel.ibindinglistview_members(v = vs.80) .aspx) – blindmeis

29

VOO的解決方案是不是爲我工作,ItemsSource爲null,則最有可能的,因爲它不直接設置,而是束縛。 我在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); 
+0

真棒方法,易於使用和修改。謝謝。 –

0

我的方法適用於我。 試試這個代碼。 DataGrid的對不起,俄羅斯

// Если таблица пустая, то привязываем ее к журналу 
      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(); 
0

PerformSort方法究竟在列的標題點擊執行。但是這種方法是內部的。所以,如果你真的想模擬點擊你需要使用反射:

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] }); 
} 
相關問題