DataGridView y INotifyCollectionChanged

I had it in my mind that if I implemented INotifyCollectionChanged on my Custom Collection that the DataGridView would subscribe to the CollectionChanged event.

My Collection implements IListSource and INotifyCollectionChanged, and has an internal BindingList. I subscribe to the ListChanged event from the BindingList and call my OnCollectionChanged method which then raises the CollectionChanged event.

Perhaps there is a better way to accomplish the above, and I would be glad to hear it. However, my primary concern at the moment is getting the DataGridView to update after this sort method is called:

    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]);
            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]);
                res = res.ThenByDescending(o => o[sortFields[x].Name]);

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

Am I mistaken in my belief that the DataGridView subscribes to the CollectionChanged event or am I doing something else wrong?

preguntado el 05 de febrero de 14 a las 07:02

1 Respuestas

Supongo que estás usando ObservableCollection<T> class for your custom collection. DataGridView no sabe sobre INotifyCollectionChanged. It is intended for WPF bindings and not to be used in WinForms.

Ver este SO question for more information.

contestado el 23 de mayo de 17 a las 13:05

Ah, ok. No, I'm not using ObservableCollection but I worked with WPF in the past a little so it sounds like I must have just gotten mixed up in thinking that DGV would support INotifyCollectionChanged. Thanks. - Vernon

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.