我编写了一个自定义Control
(一个自动完成的TextBox
(如下所示)),其中以编程方式将ContextMenuStrip
添加到表单中。
我的问题是,当控件生成的列表比它的父容器(Panel
、GroupBox
等)的高度还长时,ContextMenuStrip
的底部部分是隐藏的。
我尝试过调用.BringToFront()
,但找不到任何方法来克服这种行为。
任何帮助都将得到极大的重视,也请随意窃取控制:)
图1。
/// <summary>
/// TextBox which can auto complete words found in a table column
/// Just set DataSource and DataListField and start typing - WD
/// </summary>
public class AutoComplete : TextBox
{
public DataTable DataSource { get; set; }
public string DataListField { get; set; }
private ContextMenuStrip SuggestionList = new ContextMenuStrip();
public AutoComplete()
{
this.LostFocus += new EventHandler(AutoComplete_LostFocus);
KeyUp += new KeyEventHandler(AutoComplete_KeyUp);
SuggestionList.ItemClicked += new ToolStripItemClickedEventHandler(SuggestionList_ItemClicked);
}
void AutoComplete_LostFocus(object sender, EventArgs e)
{
if (!SuggestionList.Focused)
{
SuggestionList.Visible = false;
}
}
void SuggestionList_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
this.Text = e.ClickedItem.Text;
SuggestionList.Visible = false;
this.Focus();
SuggestionList.Visible = false;
}
void AutoComplete_KeyUp(object sender, KeyEventArgs e)
{
if (null != DataSource && DataSource.Rows.Count > 0 && null != DataListField)
{
if (e.KeyCode != Keys.Enter)
{
if (SuggestionList.Items.Count > 0 && e.KeyCode == Keys.Down)
{
SuggestionList.Focus();
SuggestionList.Items[0].Select();
SuggestionList.BringToFront();
}
else if (this.Text.Length > 0)
{
SuggestionList.Items.Clear();
DataRow[] drSuggestionList = DataSource.Select("[" + DataListField + "] LIKE '" + this.Text + "%'");
foreach (DataRow dr in drSuggestionList)
{
SuggestionList.Items.Add(dr[DataListField].ToString());
}
SuggestionList.TopLevel = false;
SuggestionList.Visible = true;
SuggestionList.Top = (this.Top + this.Height);
SuggestionList.Left = this.Left;
this.Parent.Controls.Add(SuggestionList);
SuggestionList.BringToFront();
}
}
}
}
}
发布于 2010-04-26 15:18:54
这是因为您将其TopLevel属性设置为false并将其添加到父控件的control集合中,从而将其转换为子控件。替换为:
SuggestionList.TopLevel = false;
SuggestionList.Visible = true;
SuggestionList.Top = (this.Top + this.Height);
SuggestionList.Left = this.Left;
this.Parent.Controls.Add(SuggestionList);
SuggestionList.BringToFront();
有了这个:
SuggestionList.Show(this.Parent.PointToScreen(new Point(this.Left, this.Bottom)));
注意,如果文本框太高,CMS会与文本框重叠。
https://stackoverflow.com/questions/2714124
复制相似问题