简体   繁体   English

DataGrid-如何使列排序动态,以适应绑定数据的更改?

[英]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. 我在VS2010 WPF C#项目中使用DataGrid。 I have bound the DataGrid to an ObservableCollection. 我已经将DataGrid绑定到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. 问题-我将如何安排数据网格中的排序是动态的,以便在数据更改时(在ObservableCollection中)排序保持正常。

Notes: Binding approach is via DataGrid 注意:绑定方法是通过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;
    }
}

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. 您可以在后面的代码中以及XAML中使用CollectionViewSource,XAML的源是您的数据网格的itemsource,然后可以向其中添加SortDescription。 This will keep the data sorted all the time. 这将使数据始终保持排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM