winforms 如何获取上下文菜单项附加到的TreeNode

2w3rbyxf  于 2023-02-09  发布在  其他
关注(0)|答案(1)|浏览(190)

在Winforms应用程序中,我有以下代码:

private void BtnNuevoGrupo_Click(object sender, EventArgs e)
{
    TreeNode newNode = TreDevices.Nodes[0].Nodes.Add("Nuevo grupo de validación");
    TreDevices.Nodes[0].Expand();
    TreDevices.SelectedNode = newNode;
    newNode.Tag = "IN:0";
    newNode.BeginEdit();
}

使用这段代码,我添加了一个树节点并立即开始编辑。然后,我得到了以下代码:

private async void TreDevices_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
      e.Node.ContextMenuStrip = new ContextMenuStrip();
      var itemEntrada = e.Node.ContextMenuStrip.Items.Add("Entrada");
      itemEntrada.Click += InOutItem_Click;
}

最后,我有这样的代码来在单击上下文菜单项时执行一些操作:

private async void InOutItem_Click(object? sender, EventArgs e)
{
    if (sender is not null)
    {
        var item = (ToolStripMenuItem)sender;
        ContextMenuStrip menu = (ContextMenuStrip)item.Owner;

        // HERE I NEED TO GET A REFERENCE TO THE TreeNode
    }
}

InOutItem_Click中,我需要得到一个对拥有菜单的TreeNode的引用。我该怎么做呢?
我只能通过使用item.Owner.SourceControl获得对树控件的引用。

6rqinv9w

6rqinv9w1#

您是否考虑过只使用itemEntradaTag属性?

private void TreDevices_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
    e.Node.ContextMenuStrip = new ContextMenuStrip();
    var itemEntrada = new ToolStripMenuItem
    {
        Text = "Entrada",
        Tag = e.Node,
    };
    e.Node.ContextMenuStrip.Items.Add(itemEntrada);
    itemEntrada.Click += InOutItem_Click;
}

private void InOutItem_Click(object sender, EventArgs e)
{
    if ((sender is ToolStripMenuItem tsmi) && (tsmi.Tag is TreeNode node))
    {
        var item = (ToolStripMenuItem)sender;
        ContextMenuStrip menu = (ContextMenuStrip)item.Owner;

        MessageBox.Show($"Clicked {node.Text}");
    }
}

相关问题