【问题标题】:Resort data in WPF DataGridWPF DataGrid 中的度假村数据
【发布时间】:2011-06-27 16:39:20
【问题描述】:

我有一个实时更新的简单集合。数据显示在 WPF 中的 DataGrid 中。当用户对 DataGrid 进行排序并且数据发生更改时,网格会使用新数据进行更新,但不会使用数据。

当底层集合发生变化时,有没有人找到一种处理数据的好方法?我可以很容易地确定何时发生了集合更改,但到目前为止我在求助方面还没有取得太大的成功。

发现我可以做到:

SortDescription description = grdData.Items.SortDescriptions[0];
grdData.ItemsSource = null;
grdData.ItemsSource = Data;
grdData.Items.SortDescriptions.Add(description);

if(description.PropertyName=="Value")
{
    grdData.Columns[1].SortDirection = description.Direction;
}
else
{
    grdData.Columns[0].SortDirection = description.Direction;
}

但这是相当的黑客。有什么更好的办法吗?

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    这有点棘手,很大程度上取决于底层数据源,但这是我要做的:

    首先,您需要一种可排序的数据类型。为此,我创建了一个“SortableObservableCollection”,因为我的基础数据类型是 ObservableCollection:

    public class SortableObservableCollection<T> : ObservableCollection<T>
    {        
        public event EventHandler Sorted;       
    
        public void ApplySort(IEnumerable<T> sortedItems)
        {
            var sortedItemsList = sortedItems.ToList();
    
            foreach (var item in sortedItemsList)
                Move(IndexOf(item), sortedItemsList.IndexOf(item));       
    
            if (Sorted != null)
                Sorted(this, EventArgs.Empty);
        }
    }
    

    现在,使用它作为数据源,我可以在我的 DataGrid 上检测排序并使用实际数据。为此,我在 DataGrid 的 Items 的 CollectionChanged 事件中添加了以下事件处理程序:

    ... In the constructor or initialization somewhere
    
    ItemCollection view = myDataGrid.Items as ItemCollection;
    ((INotifyCollectionChanged)view.SortDescriptions).CollectionChanged += MyDataGrid_ItemsCollectionChanged;
    
    ...
    
    private void MyDataGrid_ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        // This is how we detect if a sorting event has happend on the grid.
        if (e.NewItems != null &&
            e.NewItems.Count == 1 &&
            (e.NewItems[0] is SortDescription))
        {
            MyItem[] myItems = new MyItem[MyDataGrid.Items.Count]; // MyItem would by type T of whatever is in the SortableObservableCollection
            myDataGrid.Items.CopyTo(myItems, 0);
            myDataSource.ApplySort(myItems);  // MyDataSource would be the instance of SortableObservableCollection
        }
    } 
    

    这比使用 SortDirection 效果好一点的原因之一是在进行组合排序的情况下(对列进行排序时按住 shift 键,您会明白我的意思)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      • 2012-06-15
      • 1970-01-01
      相关资源
      最近更新 更多