Winforms绑定到ListBox
我有一个带有ListBox的Windows窗体。 表单有这种方法
public void SetBinding(BindingList _messages) { BindingList toBind = new BindingList( _messages ); lbMessages.DataSource = toBind; }
在其他地方,我有一个名为Manager的类具有此属性
public BindingList Messages { get; private set; }
并在其构造函数中的这一行
Messages = new BindingList();
最后,我有我的启动程序,实例化表单和管理器,然后调用
form.SetBinding(manager.Messages);
我还需要做什么,以便管理器中的声明如下:
Messages.Add("blah blah blah...");
将导致一行添加到窗体的ListBox中并立即显示?
我根本不需要这样做。 我只是希望我的Manager类能够在它完成工作时发布到表单。
我认为问题在于你在SetBinding
方法中创建一个新的绑定列表,这意味着你不再绑定到Manager对象中的列表了。
尝试将当前的BindingList传递给数据源:
public void SetBinding(BindingList messages) { // BindingList toBind = new BindingList (messages); lbMessages.DataSource = messages; }
添加一个新的Winforms项目。 删除ListBox。 请原谅设计。 只是想通过使用BindingSource和BindingList组合来表明它的工作原理。
使用BindingSource是关键
经理class
public class Manager { /// /// BindingList fires ListChanged event when a new item is added to the list. /// Since BindingSource hooks on to the ListChanged event of BindingList it also is /// “aware” of these changes and so the BindingSource fires the ListChanged event. /// This will cause the new row to appear instantly in the List, DataGridView or make any /// controls listening to the BindingSource “aware” about this change. /// public BindingList Messages { get; set; } private BindingSource _bs; private Form1 _form; public Manager(Form1 form) { // note that Manager initialised with a set of 3 values Messages = new BindingList {"2", "3", "4"}; // initialise the bindingsource with the List - THIS IS THE KEY _bs = new BindingSource {DataSource = Messages}; _form = form; } public void UpdateList() { // pass the BindingSource and NOT the LIST _form.SetBinding(_bs); } }
Form1类
public Form1() { mgr = new Manager(this); InitializeComponent(); mgr.UpdateList(); } public void SetBinding(BindingSource _messages) { lbMessages.DataSource = _messages; // NOTE that message is added later & will instantly appear on ListBox mgr.Messages.Add("I am added later"); mgr.Messages.Add("blah, blah, blah"); }