我在 Winforms 中遇到了看似简单的问题。
我想实现一个可以用作列表框数据源的集合。我打算将它用于简单的字符串。像这样:
MyBindingCollection<string> collection = new MyBindingCollection<string>();
listbox.DataSource = collection;
我读到我需要实现的只是IList
接口(interface)。但是,我希望列表框在我这样做时自行更新:
collection.Add('test');
collection.RemoveAt(0):
如何创建这样的集合?这只是单向绑定(bind),我不需要从 GUI 更新集合。 (列表框是只读的)。
最佳答案
尝试使用 BindingList<T>
它适用于单向和双向绑定(bind)。
BindingList<string> list = new BindingList<string>();
listbox.DataSource = list;
list.Add("Test1");
list.Add("Test2");
list.RemoveAt(0);
编辑:
添加了带有 IBindingList
的示例解决方案
您不必为 IBindingList
实现所有方法界面。
那些你不需要的只是扔一个 NotImplementedException
.
public class MyBindingList : IBindingList
{
private readonly List<string> _internalList = new List<string>();
public int Add(object value)
{
_internalList.Add(value.ToString());
var listChanged = ListChanged;
var newIndex = _internalList.Count - 1;
if (listChanged != null)
{
listChanged(this, new ListChangedEventArgs(ListChangedType.ItemAdded, newIndex));
}
return newIndex;
}
public event ListChangedEventHandler ListChanged;
public int IndexOf(object value) // No need for this method
{
throw new NotImplementedException();
}
// + all other methods on IBindingList interface
}
关于c# - 如何为 Listbox DataSource 实现一种方式绑定(bind)集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2684094/