[英]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.