[英]DataGrid - how to make Column sorting dynamic, to cater for when bound data changes?
我在VS2010 WPF C#项目中使用DataGrid。 我已经将DataGrid绑定到ObservableCollection。 当您单击列标题时,它将在该时间点对数据进行排序。
问题-我将如何安排数据网格中的排序是动态的,以便在数据更改时(在ObservableCollection中)排序保持正常。
注意:绑定方法是通过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;
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;
}
}
您可以在后面的代码中以及XAML中使用CollectionViewSource,XAML的源是您的数据网格的itemsource,然后可以向其中添加SortDescription。 这将使数据始终保持排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.