2012-02-19 36 views
0

如何在DataGrid.ItemsSource == null時實現自定義排序?我已經使用DataGrid.Items.Add()將項增量添加到DataGrid,而不是分配ItemsSource,因此我的ItemsSource總是顯示爲空。我想使用這樣的排序處理程序(下面)但((DataGrid)發件人).ItemsSource始終爲空。該怎麼辦?如何在ItemsSource == null時對DataGrid列執行自定義排序?

public void SortHandler(object sender, DataGridSortingEventArgs e) 
    { 
     DataGridColumn column = e.Column; 

     if (column.DisplayIndex == 1) 
     { 
      IComparer comparer = null; 

      //i do some custom checking based on column to get the right comparer 
      //i have different comparers for different columns. I also handle the sort direction 
      //in my comparer 

      // prevent the built-in sort from sorting 
      e.Handled = true; 

      ListSortDirection direction = (column.SortDirection != ListSortDirection.Ascending) ? ListSortDirection.Ascending : ListSortDirection.Descending; 

      //set the sort order on the column 
      column.SortDirection = direction; 

      //use a ListCollectionView to do the sort. 
      ListCollectionView lcv = (ListCollectionView)CollectionViewSource.GetDefaultView(((DataGrid)sender).ItemsSource);     

      //this is my custom sorter it just derives from IComparer and has a few properties 
      //you could just apply the comparer but i needed to do a few extra bits and pieces 
      comparer = new MySort(direction, column); 

      //apply the sort 
      lcv.CustomSort = comparer; 
     } 
     else 
     { 
      e.Handled = false; 
     } 
    } 

回答

0

WPF的強大功能是綁定支持,所以爲什麼不使用它。所以,我建議你將你的dataGrid的ItemSource綁定到你的類中的ObservableCollection,並將這些項添加到這個集合中。

您使用ObservableCollection獲得的好處是它實現了INotifyCollectionChanged,這樣您就不必擔心UI刷新問題。只要添加項目,項目就會在您的用戶界面上更新。您也可以使用CollectionViewSource。參考這篇文章 - http://bea.stollnitz.com/blog/?p=387

相關問題