Winforms绑定到列表框

本文关键字:列表 绑定 Winforms | 更新日期: 2023-09-27 18:36:59

我有一个带有ListBox的Windows表单。 表单具有此方法

public void SetBinding(BindingList<string> _messages)
{
  BindingList<string> toBind = new BindingList<string>( _messages );
  lbMessages.DataSource = toBind;
}

在其他地方,我有一个名为管理器的类,它具有此属性

public BindingList<string> Messages { get; private set; }

以及其构造函数中的这一行

Messages = new BindingList<string>();

最后,我有我的启动程序,它实例化表单和管理器,然后调用

form.SetBinding(manager.Messages);

我还需要做什么才能在管理器中生成这样的语句:

Messages.Add("blah blah blah...");

是否会导致在窗体的列表框中添加并立即显示一行?

我完全不必这样做。 我只是希望我的经理类能够在表单完成工作时发布到表单。

Winforms绑定到列表框

我认为问题出在您的SetBinding方法上,您正在创建一个新的绑定列表,这意味着您不再绑定到管理器对象中的列表。

尝试将当前绑定列表传递给数据源:

public void SetBinding(BindingList<string> messages)
{
  // BindingList<string> toBind = new BindingList<string>(messages);
  lbMessages.DataSource = messages;
}

添加新的 WinForms 项目。删除列表框。请原谅设计。只是想表明它的工作原理是你想要通过使用BindingSource和BindingList组合来实现的。

使用绑定源是这里的关键

经理类

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);
    }
}

中一类

   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");
    }