2012-03-05 44 views
7

Tôi cần biết khi nào WPF Datagrid đã được người dùng sắp xếp. Tại sao không có sự kiện Sorted? Tôi chỉ có thể tìm thấy sự kiện Sắp xếp.DataGrid: Không có sự kiện Sắp xếp?

Tôi cũng đã điều tra CollectionViewListCollectionView để lộ các đối tượng vào Chế độ xem mà không có bất kỳ sự may mắn nào.

Tôi khá ngạc nhiên vì điều này sẽ ra khỏi hộp. Bất kỳ ý tưởng nào?

+0

MSDN có thể là một nơi tốt hơn để hỏi "tại sao". –

+0

Xử lý Sắp xếp và chỉ chuyển loại cho DataGrid. – Paparazzi

+0

xử lý sắp xếp? Bạn có nghĩa là phân loại? – Houman

Trả lời

1

DataGrid có sự kiện "Sắp xếp", đăng ký sự kiện!

XAML:

<DataGrid ItemsSource="{Binding YourItems}" AutoGenerateColumns="True" anUserSortColumns="True" 
      Sorting="DataGrid_Sorting"/> 

cs mã:

private void DataGrid_Sorting(object sender, System.Windows.Controls.DataGridSortingEventArgs e) 
{ 
    Console.WriteLine(string.Format("sorting grid by '{0}' column in {1} order", e.Column.SortMemberPath, e.Column.SortDirection)); 
} 
+1

điều này chắc chắn nên đã được chấp nhận – Jonesopolis

+3

Đây không phải là câu trả lời đúng. OP đặc biệt nói rằng anh ta muốn một sự kiện được sắp xếp, không phải là một sự kiện sắp xếp. Sự khác biệt là liệu các mục đã được sắp xếp chưa. Nhận xét của Oliver Dufner chỉ tới [câu hỏi trùng lặp] (http://stackoverflow.com/questions/8416961/how-can-i-be-notified-if-a-datagrid-column-is-sorted-and-not-sorting) là câu trả lời chính xác. – Wally

1

Tôi đã lấy một ví dụ từ MSDN documentation và điều chỉnh nó để nâng cao một sự kiện Sắp xếp khi sự kiện Sorting được thực hiện.

public class CustomDataGrid : DataGrid 
{ 
    // Create a custom routed event by first registering a RoutedEventID 
    // This event uses the bubbling routing strategy 
    public static readonly RoutedEvent SortedEvent = EventManager.RegisterRoutedEvent(
     "Sorted", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CustomDataGrid)); 

    // Provide CLR accessors for the event 
    public event RoutedEventHandler Sorted 
    { 
     add { AddHandler(SortedEvent, value); } 
     remove { RemoveHandler(SortedEvent, value); } 
    } 

    // This method raises the Sorted event 
    void RaiseSortedEvent() 
    { 
     RoutedEventArgs newEventArgs = new RoutedEventArgs(CustomDataGrid.SortedEvent); 
     RaiseEvent(newEventArgs); 
    } 

    protected override void OnSorting(DataGridSortingEventArgs eventArgs) 
    { 
     base.OnSorting(eventArgs); 
     RaiseSortedEvent(); 
    } 
} 

Sau đó, bạn có thể sử dụng tính năng này trong codebehind.

datagrid.Sorted += new RoutedEventHandler(datagrid_Sorted); 

hoặc trong XAML

<local:CustomDataGrid x:Name="datagrid" Sorted="datagrid_Sorted;"/> 
Các vấn đề liên quan