2010-10-04 25 views
0

我在VS2010 WPF C#項目中使用DataGrid。我已經將DataGrid綁定到ObservableCollection。當你點擊一個列標題時,它會在那個時間點對數據進行排序。DataGrid - 如何使列動態排序,以適應綁定數據更改?

問題 - 如何安排DataGrid中的排序是動態的,以便在數據更改時(在ObservableCollection內)排序繼續工作。

注:綁定的方法是通過數據網格

private ObservableCollection<SummaryItem> _summaryData = new ObservableCollection<SummaryItem>(); 
SummaryDataGrid.ItemsSource = _summaryData; 

SummaryDataGrid.AutoGeneratingColumn += (s, e) => 
{ 
    //if (e.Column.Header.ToString() == "ProcessName") 
    // e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star); 
    e.Column.Width = new DataGridLength(1, DataGridLengthUnitType.Star); 
}; 

public class SummaryItem : INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    private string _processName; 
    public string ProcessName 
    { 
     get { return _processName; } 
     set 
     { 
      _processName = value; 
      NotifyPropertyChanged("ProcessName"); 
     } 
    } 

    private long _total; 
    public long Total 
    { 
     get { return _total; } 
     set 
     { 
      _total = value; 
      NotifyPropertyChanged("Total"); 
     } 
    } 

    private long _average; 
    public long Average 
    { 
     get { return _average; } 
     set 
     { 
      _average = value; 
      NotifyPropertyChanged("Average"); 
     } 
    } 

    private void NotifyPropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs((propertyName))); 
     } 
    } 

    public static SummaryItem ObservableCollectionSearch(ObservableCollection<SummaryItem> oc, string procName) 
    { 
     foreach (var summaryItem in oc) 
     { 
      if (summaryItem.ProcessName == procName) return summaryItem; 
     } 
     return null; 
    } 
} 

回答

1

可以在代碼中使用CollectionViewSource背後,以及在XAML,它的來源是你的DataGrid的的ItemSource,那麼你可以添加SortDescription/s到它。這將保持數據一直排序。

相關問題