Datagrid-列の並べ替えを動的にする方法、バインドされたデータが変更されたときに対応する方法は?

StackOverflow https://stackoverflow.com/questions/3852356

質問

VS2010 WPF C#プロジェクトでDatagridを使用しています。 Datagridを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;
    }
}
役に立ちましたか?

解決

CollectionViewSourceを背後にコードで使用し、そのソースがDatagridのItemourceであるXamlで使用できます。その後、SortDescription/sを追加できます。これにより、データは常にソートされます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top