代码之家  ›  专栏  ›  技术社区  ›  Greg

DataGrid—如何使列排序动态化,以满足绑定数据更改时的需要?

  •  0
  • Greg  · 技术社区  · 14 年前

    我正在VS2010 wpfc项目中使用DataGrid。我已将DataGrid绑定到ObservableCollection。当您单击列标题时,它会在该时间点对数据进行排序。

    问题-我如何安排使DataGrid中的排序是动态的,以便当数据发生变化时(在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;
        }
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Bhupendra    14 年前

    您可以在代码隐藏和XAML中使用CollectionViewSource,XAML的源代码是您的datagrid的itemsource,然后您可以向其中添加SortDescription。这将一直保持数据的排序。