c# - 如何为 Listbox DataSource 实现一种方式绑定(bind)集合?

标签 c# winforms data-binding listbox

我在 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/

相关文章:

c# - 生成资源任务失败错误

vb.net - WinForms 深度嵌套控件调整内核大小错误 - 拆分器面板无法正确缩放控件

c# - 如何防止多次打开我的应用程序?

WPF 数据绑定(bind)到链表

html - 有没有一种简单的方法可以让 dojo/dijit 工具包与 knockout observables 一起工作?

c# - 如何在 C# 3.5 中对泛型方法施加接口(interface)约束?

c# - Windows 模拟 LogonUser 错误

c# - 绑定(bind)源刷新

c# - 获取属性名称的 Linq 表达式和扩展方法

c# - 如何转换此日期并保存到数据库