winformsbindingtoolstripdropdowntoolstripcontrolhost

ListControl.DataSource in ToolStipControlHost not function


I use a ToolStripControlHost to wrap a ListBox control for adding it into a ToolStripDropDown, but found items I assign to ListBox.DataSource not shown up, and ComboBox.DataSource not work as well, I don't understand why ListContorl.DataSource not function in ToolStripControlHost.

        ListBox listBox = new ListBox();
        listBox.DataSource = new string[] { "1", "2", "3" };

        ToolStripControlHost host = new ToolStripControlHost(listBox)
        {
            Margin = Padding.Empty,
            Padding = Padding.Empty,
            AutoSize = false
        };

        ToolStripDropDown dropDown = new ToolStripDropDown() { AutoClose = false };
        dropDown.Items.Add(host);
        dropDown.Show();

Edit

I found the problem is ToolStripDropDown has not parents to provide BindingContext, so it will happen to any control with DataManager.


Solution

  • I found the problem is ToolStripDropDown has no parents to provide a BindingContext, so the solution is assign the BindingContext of the Form.

            ListBox listBox = new ListBox();
            listBox.DataSource = new string[] { "1", "2", "3" };
            listBox.BindingContext = this.BindingContext; //assign a BindingContext
    
            ToolStripControlHost host = new ToolStripControlHost(listBox)
            {
                Margin = Padding.Empty,
                Padding = Padding.Empty,
                AutoSize = false
            };
    
            ToolStripDropDown dropDown = new ToolStripDropDown() { AutoClose = false };
            dropDown.Items.Add(host);
            dropDown.Show();