1

我的想法是,如果我在自定义集合上实现 INotifyCollectionChanged,DataGridView 将订阅 CollectionChanged 事件。

我的 Collection 实现了 IListSource 和 INotifyCollectionChanged,并且有一个内部 BindingList。我从 BindingList 订阅 ListChanged 事件并调用我的 OnCollectionChanged 方法,然后引发 CollectionChanged 事件。

也许有更好的方法来完成上述任务,我很高兴听到它。但是,我目前主要关心的是在调用此排序方法后让 DataGridView 更新:

    public void Sort(List<SortField> sortFields)
    {
        if(sortFields == null || sortFields.Count == 0) return;

        IOrderedEnumerable<T> res;

        if (sortFields[0].Ascending)
            res = _items.OrderBy(o => o[sortFields[0].Name]);
        else
            res = _items.OrderByDescending(o => o[sortFields[0].Name]);

        for (int x = 1; x < sortFields.Count; x++)
            if (sortFields[x].Ascending)
                res = res.ThenBy(o => o[sortFields[x].Name]);
            else
                res = res.ThenByDescending(o => o[sortFields[x].Name]);

        Items = new BindingList<T>(res.ToList());
        OnListChanged(this, new ListChangedEventArgs(ListChangedType.Reset, null));
    }

我是否误以为 DataGridView 订阅了 CollectionChanged 事件,或者我做错了什么?

4

1 回答 1

1

我假设您正在ObservableCollection<T>为您的自定义集合使用类。DataGridView不知道INotifyCollectionChanged。它旨在用于 WPF 绑定,而不是用于WinForms.

有关更多信息,请参阅SO 问题。

于 2014-02-05T08:36:55.790 回答