【问题标题】:How to implement one way binding collection for Listbox DataSource?如何为 Listbox DataSource 实现单向绑定集合?
【发布时间】:2011-02-10 15:54:47
【问题描述】:

我在 Winforms 中遇到了看似简单的问题。

我想实现一个可以用作列表框数据源的集合。我打算将它用于简单的字符串。像这样:

MyBindingCollection<string> collection = new MyBindingCollection<string>();
listbox.DataSource = collection;

我读过我需要实现的只是IList 接口。但是,我希望列表框在我这样做时自行更新:

collection.Add('test');
collection.RemoveAt(0):

如何创建这样的集合?这只是单向绑定,我不需要从 GUI 更新集合。 (列表框是只读的)。

【问题讨论】:

    标签: c# winforms data-binding listbox


    【解决方案1】:

    尝试使用BindingList&lt;T&gt;,它适用于单向绑定和双向绑定。

    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
    }
    

    【讨论】:

    • 问题是我对这个集合有特定的需求,并且想要实现我自己的内部结构。所以 BindingList 可能是没有问题的。
    • @Kugel,然后您可以创建自己的类并从 BindingList 继承或实现 IBindingList。
    • @Kugel,更新 listBox 的事件是 IBindingList.ListChanged 事件,因此如果您的集合正在实现 IBindingList,那么这就是您需要实现的全部内容。其他一切你都可以抛出 NotImplementedException。
    猜你喜欢
    • 1970-01-01
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 2015-09-01
    • 2018-02-14
    • 1970-01-01
    • 2011-07-10
    相关资源
    最近更新 更多