2013-07-19 528 views
1

我需要禁用DataGrid上的多列排序。這可能嗎?如何在wpf DataGrid上禁用多列排序?

+0

你能向我們展示一些關於目前爲止的代碼? – TheGeekZn

+0

@NewAmbition:當然,我有一個DataGrid和一個自定義的分類器,但我不確定這是否會對您有所幫助...... –

+0

好吧,在您正在編寫的代碼中提供答案會更容易如果我們知道你的代碼是什麼的話。 – TheGeekZn

回答

1

我通過訂閱DataGrid_Sorting事件的Args' Handled屬性設置爲true,取得了成功:

private void ResultsDataGrid_Sorting(object sender, DataGridSortingEventArgs e) 
{ 
    if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) 
    { 
     e.Handled = true; 
    } 
} 
+0

不錯的。我會用一種行爲來做 –

0

你可以創建一個行爲,並處理排序是你自己。 以下沒有測試:)

public class DataGridICollectionViewSortMerkerBehavior : Behavior<DataGrid> 
{ 
    protected override void OnAttached() 
    { 
     base.OnAttached(); 
     AssociatedObject.Sorting += AssociatedObjectSorting; 
    } 

    protected override void OnDetaching() 
    { 
     base.OnDetaching(); 
     AssociatedObject.Sorting -= AssociatedObjectSorting; 
    } 

    void AssociatedObjectSorting(object sender, DataGridSortingEventArgs e) 
    { 
     var view = AssociatedObject.ItemsSource as ICollectionView; 
     var propertyname = e.Column.SortMemberPath; 

     e.Column.SortDirection = this.GetSortArrowForColumn(e.Column); 

     if (view == null) 
      return; 

     view.SortDescriptions.Clear();    
     var sort = new SortDescription(propertyname, (ListSortDirection)e.Column.SortDirection); 
     view.SortDescriptions.Add(sort); 


     e.Handled = true; 
    } 


    private ListSortDirection GetSortArrowForColumn(DataGridColumn col) 
    { 
     if (col.SortDirection == null) 
     { 
      return ListSortDirection.Ascending; 
     } 
     else 
     { 
      return col.SortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending; 
     } 
    } 
    } 

XAML

<DataGrid ...> 
    <i:Interaction.Behaviors> 
      <Kadia:DataGridICollectionViewSortMerkerBehavior /> 
    </i:Interaction.Behaviors> 
+0

只適用於ICollectionView「castable」itemssources。 – blindmeis

+0

mhh更簡單應該是禁用PreviewMouseDown中的Shift修飾符... – blindmeis

+0

如何檢查Shift鍵的狀態或修改它? –