我使用ToolStripControlHost包装一个ListBox控件,以便将它添加到ToolStripDropDown中,但发现分配给ListBox.DataSource的项没有显示,ComboBox.DataSource也不工作,我不明白为什么ListContorl.DataSource在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();编辑
我发现问题是ToolStripDropDown没有父母提供BindingContext,所以它会发生在DataManager的任何控制上。
发布于 2015-10-27 03:13:05
我发现问题是ToolStripDropDown没有父级来提供BindingContext,所以解决方案是分配表单的BindingContext。
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();发布于 2015-10-06 03:41:54
问得好。似乎必须将ListBox添加到顶级控件(如Form)中,才能强制它使用DataSource属性。例如,在分配DataSource之后添加此代码:
public class DataForm : Form {
ToolStripDropDown dropDown = new ToolStripDropDown() { AutoClose = true };
ListBox listBox = new ListBox();
public DataForm() {
listBox.DataSource = new string[] { "1", "2", "3" };
var hWnd = listBox.Handle; // required to force handle creation
using (var f = new Form()) {
f.Controls.Add(listBox);
f.Controls.Remove(listBox);
}
ToolStripControlHost host = new ToolStripControlHost(listBox) {
Margin = Padding.Empty,
Padding = Padding.Empty,
AutoSize = false
};
dropDown.Items.Add(host);
}
protected override void OnMouseClick(MouseEventArgs e) {
base.OnMouseClick(e);
dropDown.Show(Cursor.Position);
}
}您还可以查看ListBox.cs源代码,试图找出根本原因:http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/ListBox.cs,03c7f20ed985c1fc。
https://stackoverflow.com/questions/32961035
复制相似问题