我有一个带有ListBox的Windows窗体。表单有这个方法
public void SetBinding(BindingList<string> _messages)
{
BindingList<string> toBind = new BindingList<string>( _messages );
lbMessages.DataSource = toBind;
}
在其他地方,我有一个名为Manager的类,它具有此属性
public BindingList<string> Messages { get; private set; }
并在其构造函数中的这一行
Messages = new BindingList<string>();
最后,我的启动程序实例化了表单和管理器,然后调用
form.SetBinding(manager.Messages);
我还需要做什么才能在Manager中发表如下声明:
Messages.Add("blah blah blah...");
会导致在表单的ListBox中添加一行并立即显示吗?
我根本不需要这样做。我只是希望我的Manager类能够在它完成工作时发布到表单。
答案 0 :(得分:3)
我认为问题在于您使用SetBinding
方法创建新绑定列表,这意味着您不再绑定到Manager对象中的列表。
尝试将当前的BindingList传递给数据源:
public void SetBinding(BindingList<string> messages)
{
// BindingList<string> toBind = new BindingList<string>(messages);
lbMessages.DataSource = messages;
}
答案 1 :(得分:1)
添加新的Winforms项目。删除ListBox。请原谅设计。只是想通过使用BindingSource和BindingList组合来表明它的工作原理。
使用 BindingSource 是关键
经理类
public class Manager
{
/// <summary>
/// BindingList<T> fires ListChanged event when a new item is added to the list.
/// Since BindingSource hooks on to the ListChanged event of BindingList<T> 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.
/// </summary>
public BindingList<string> 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<string> {"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");
}