DataGrid - how to make Column sorting dynamic, to cater for when bound data changes?
I'm using a DataGrid in a VS2010 WPF C# project. I have bound the DataGrid to an ObservableCollection. When you click on a column heading it sorts the data at that point in time.
Question - How would I arrange such that the sorting in the DataGrid is dynamic, so that when data changes (within the ObservableCollection) the sorting keeps working.
Notes: Binding approach is via DataGrid
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;
Noti开发者_Go百科fyPropertyChanged("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;
}
}
You can use CollectionViewSource in code behind as well as in XAML, whose source is your datagrid's itemsource, then you can add the SortDescription/s to it. This will keep the data sorted all the time.
精彩评论