How to implement a single binding assembly for a Listbox DataSource?

I seem to have a simple problem in Winforms.

I want to implement a collection that can be used as a DataSource for a list. I intend to use it for simple strings. For instance:

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

I read that all I need to implement is an interface IList. However, I would like listbox to update when I do:

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

How to create such a collection? This is only a one-way binding, I do not need to update the collection from the GUI. (read-only listbox).

+3
source share
1 answer

BindingList<T>, , .

BindingList<string> list = new BindingList<string>();
listbox.DataSource = list;

list.Add("Test1");
list.Add("Test2");
list.RemoveAt(0);

Edit:
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
}
+3

Source: https://habr.com/ru/post/1742119/


All Articles