DataGrid的 - 如何让列进行排序的动态,以满足当绑定数据的变化?
-
27-09-2019 - |
题
我使用的VS2010 WPF C#项目一个DataGrid。我已绑定的DataGrid中到一个ObservableCollection。当您在列标题点击它在那个时间点的数据进行排序。
问题 - 如何将予安排,使得在数据网格排序是动态的,因此,当(在的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;
}
}
解决方案
您可以在代码中使用CollectionViewSource背后,以及在XAML,它的来源是你的DataGrid的的ItemSource,那么你可以添加SortDescription / s到它。这将保持数据排序的所有的时间。
不隶属于 StackOverflow