[英]How do I prevent my ContextMenu from being constrained to its container (Win Forms c#)
我寫了一個自定義的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();
}
}
}
}
}
這是因為您通過將其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太高,它將與文本框重疊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.