2

我有一个带有 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 类能够在其工作时发布到表单。

4

2 回答 2

3

我认为问题出SetBinding在您制作绑定列表的方法上,这意味着您不再绑定到 Manager 对象中的列表。

尝试将当前的 BindingList 传递给数据源:

public void SetBinding(BindingList<string> messages)
{
  // BindingList<string> toBind = new BindingList<string>(messages);
  lbMessages.DataSource = messages;
}
于 2012-06-12T14:51:09.787 回答
1

添加一个新的 Winforms 项目。删除一个列表框。原谅设计。只是想表明它可以通过使用 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");
    }
于 2012-06-12T17:09:42.787 回答