嗨我在标签上添加了一个上下文菜单(c#,winforms)。我的上下文菜单有3个子项,我想在我点击任何一个上下文菜单项时显示标签文本。
提前致谢
ContextMenuStrip
控件有一个SourceControl
属性,它将引用打开它的控件。您可以使用它从控件中提取文本:
private void MenuStripItem_Click(object sender, EventArgs e)
{
ToolStripItem item = (sender as ToolStripItem);
if (item != null)
{
ContextMenuStrip owner = item.Owner as ContextMenuStrip;
if (owner != null)
{
MessageBox.Show(owner.SourceControl.Text);
}
}
}
如果您使用ContextMenuStrip
代替ContextMenu
,代码应如下所示:
private void menuItem1_Click(object sender, EventArgs e)
{
MenuItem item = (sender as MenuItem);
if (item != null)
{
ContextMenu owner = item.Parent as ContextMenu;
if (owner != null)
{
MessageBox.Show(owner.SourceControl.Text);
}
}
}
获取上下文菜单父控件名称MessageBox.Show(contextMenuStrip1.SourceControl.Name.ToString());
它是一线中最好的:
Control control = ((ContextMenuStrip)((ToolStripItem)sender).Owner).SourceControl;