上下文菜单父级?

发布于 2024-08-05 20:01:39 字数 88 浏览 1 评论 0原文

您好,我在标签上添加了一个上下文菜单(c#,winforms)。我的上下文菜单有 3 个子项,我想在单击任一上下文菜单项时显示标签文本。

提前致谢

Hi I added a context menu on label (c#, winforms). my context menu having 3 child items and i want to display label text when i click on any one of context menu items.

thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

圈圈圆圆圈圈 2024-08-12 20:01:39

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);
        }
    }
}

如果您使用 ContextMenu 而不是 ContextMenuStrip,则代码应如下所示:

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);
        }
    }
}

The ContextMenuStrip control has a SourceControl property, that will have a reference to the control that opened it. You can use that to extract the text from the control:

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);
        }
    }
}

If you instead of a ContextMenuStrip use a ContextMenu, the code should look like this:

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);
        }
    }
}
り繁华旳梦境 2024-08-12 20:01:39

这是一行中最好的:

Control control = ((ContextMenuStrip)((ToolStripItem)sender).Owner).SourceControl;

Its the best in one line:

Control control = ((ContextMenuStrip)((ToolStripItem)sender).Owner).SourceControl;
走野 2024-08-12 20:01:39

获取上下文菜单父控件名称
MessageBox.Show(contextMenuStrip1.SourceControl.Name.ToString());

Get Context Menu Parent Control Name
MessageBox.Show(contextMenuStrip1.SourceControl.Name.ToString());

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文