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 プロジェクトを追加します。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");
    }
于 2012-06-12T17:09:42.787 に答える