[英]Binding a BindingList to a collection
I have a library that returns a collection like this: 我有一个图书馆,它返回这样的集合:
public IEnumerable Alerts { .. } IEnumerable公共警报{..}
and I want to turn this collection into a BindingList for use in the GUI. 我想将此集合转换为BindingList以在GUI中使用。 What is the best way to keep a BindingList synchronised with an IEnumerable collection?
使BindingList与IEnumerable集合保持同步的最佳方法是什么?
edit: For this problem, assume I have no control of the library and the actual implementation uses a List. 编辑:对于此问题,假定我无法控制该库,并且实际实现使用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? 该库还具有与AddAlert,RemoveAlert等的良好接口。使GUI与所有这些更改保持同步的最佳方法是什么?
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: 假设您要包装的类公开了
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
}
This should result in the lists staying in sync as you manipulate them. 这将导致列表在您操作它们时保持同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.