C# DataGridView和InotifyCollection已更改

C# DataGridView和InotifyCollection已更改,c#,winforms,collections,datagridview,inotifycollectionchanged,C#,Winforms,Collections,Datagridview,Inotifycollectionchanged,我认为,如果在自定义集合上实现INotifyCollectionChanged,DataGridView将订阅CollectionChanged事件 我的集合实现了IListSource和INotifyCollectionChanged,并具有内部绑定列表。我从BindingList订阅ListChanged事件,并调用OnCollectionChanged方法,该方法随后引发CollectionChanged事件 也许有更好的方法来实现上述目标,我很高兴听到这一点。但是,我目前主要关心的是在调

我认为,如果在自定义集合上实现INotifyCollectionChanged,DataGridView将订阅CollectionChanged事件

我的集合实现了IListSource和INotifyCollectionChanged,并具有内部绑定列表。我从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));
    }
公共无效排序(列出排序字段)
{
if(sortFields==null | | sortFields.Count==0)返回;
不可数目;
if(排序字段[0]。升序)
res=_items.OrderBy(o=>o[sortFields[0].Name]);
其他的
res=_items.OrderByDescending(o=>o[sortFields[0].Name]);
for(int x=1;xo[sortFields[x].Name]);
其他的
res=res.thenby降序(o=>o[sortFields[x].Name]);
Items=新绑定列表(res.ToList());
OnListChanged(这是新的ListChangedEventArgs(ListChangedType.Reset,null));
}

我是否错误地认为DataGridView订阅了CollectionChanged事件,或者我做了其他错误的事情?

我假设您正在为自定义集合使用
ObservableCollection
DataGridView
不知道
INotifyCollectionChanged
。它用于WPF绑定,不用于
WinForms


更多信息请参见SO问题。

啊,好的。不,我没有使用ObservableCollection,但我在过去曾与WPF合作过一段时间,所以听起来我一定是混淆了DGV将支持INotifyCollectionChanged的想法。谢谢