开发者

How to implement one way binding collection for Listbox DataSource?

开发者 https://www.devze.com 2022-12-27 12:08 出处:网络
I have seemingly simple problem in Winforms. I want to implement a collectio开发者_StackOverflow中文版n that can be used as a DataSource for a listbox. I intend to use it for simple strings. Like so:

I have seemingly simple problem in Winforms.

I want to implement a collectio开发者_StackOverflow中文版n that can be used as a DataSource for a listbox. I intend to use it for simple strings. Like so:

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

I've read that all I need to implement is IList interface. However I would like the listbox to update itself when I do:

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

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


Try using BindingList<T> it works for both one way and bidirectional binding.

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

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

Edit:
Added a sample solution with IBindingList
You don´t have to implement all the methods for the IBindingList interface.
The ones you don´t need just throw an 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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消