将BindingList绑定到集合

时间:2010-02-02 16:25:37

标签: c# .net bindinglist

我有一个库,可以返回这样的集合:

公共IEnumerable警报{..}

我希望将此集合转换为用于GUI的BindingList。保持BindingList与IEnumerable集合同步的最佳方法是什么?

编辑:对于这个问题,假设我无法控制库,实际实现使用List 但我不想触摸这段代码。

这个库与AddAlert,RemoveAlert等有一个很好的接口。保持GUI与所有这些变化同步的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

假设你要包装的课程暴露了Insert这样的内容,你应该能够从BindingList<T>派生出来,覆盖一些关键方法 - 例如:

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
}

这会导致列表在您操作时保持同步。