2012-06-12 141 views
2

我有一个带有ListBox的Windows窗体。窗体有这种方法Winforms绑定到列表框

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

将导致添加到线,并在窗体的列表框立即显示?

我根本没必要这样做。我只想让我的经理类能够在其工作时发布到表单。

回答

3

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

尽量只传递当前的BindingList到数据源:

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

我试过了,但Manager中的Messages.Add语句不会更新lbMessages.DataSource;它的数量永远不会从0移动。 –

+0

@KellyCline我试着尽可能地模仿你的代码,当我在Manager类中弹出消息时,ListBox自动显示新消息。确保你引用的是同一个Manager类。否则,您可能需要更新您的文章以获取更多信息。 – LarsTech

1

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

使用的BindingSource是这里的关键

Manager类

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

另一个评论提供了一个修复,但我也想试试这个。谢谢! –

+0

'典型的解决方案程序员将使用提供数据绑定功能的类,例如** BindingSource **,而不是直接使用BindingList 。阅读备注部分 - http://msdn.microsoft.com/en-us /library/ms132679.aspx –