views:

41

answers:

1

I have a library that returns a collection like this:

public IEnumerable Alerts { .. }

and I want to turn this collection into a BindingList for use in the GUI. What is the best way to keep a BindingList synchronised with an IEnumerable collection?

edit: For this problem, assume I have no control of the library and the actual implementation uses a List.
But I do not want to touch this code.

This library also has a nice interface with AddAlert, RemoveAlert etc. What is the best way to keep the GUI synchronised with all these changes?

A: 

Assuming the class you are wrapping exposes things like Insert, you should just be able to derive from BindingList<T>, overriding a few key methods - something like:

class MyList<T> : BindingList<T>
{
    private readonly Foo<T> wrapped;
    public MyList(Foo<T> wrapped)
        : base(new List<T>(wrapped.Items))
    {
        this.wrapped = wrapped;
    }
    protected override void InsertItem(int index, T item)
    {
        wrapped.Insert(index, item);
        base.InsertItem(index, item);            
    }
    protected override void RemoveItem(int index)
    {
        wrapped.Remove(this[index]);
        base.RemoveItem(index);
    }
    protected override void ClearItems()
    {
        wrapped.Clear();
        base.ClearItems();
    }
    // possibly also SetItem
}

This should result in the lists staying in sync as you manipulate them.

Marc Gravell
Thank you but it does not quite work. If the collection in the library changes in some other manner (not via the user through the GUI) the listbox won't synchronise with the new collection.
DanDan