gpt4 book ai didi

c# - 从上下文菜单项事件处理程序获取树节点

转载 作者:行者123 更新时间:2023-11-30 14:13:31 25 4
gpt4 key购买 nike

我有一个包含多个树节点的 TreeView 。当我右键单击一个树节点时,我得到一个上下文菜单具有不同的选项,例如“删除项目”。

有没有一种简单的方法可以在 contextmenu-item 的 eventHandler 中获取右键单击的树节点对象?

最佳答案

前段时间我遇到了类似的问题,我想出了这样的解决方案

创建您自己的派生自标准 ContextMenuStrip 的 myContextMenuStrip 类

    public class myContextMenuStrip : ContextMenuStrip
{
public TreeNode tn;

public myContextMenuStrip() { }

protected override void OnItemClicked(ToolStripItemClickedEventArgs e)
{
base.OnItemClicked(e);
if (e.ClickedItem.Text == "asd") MessageBox.Show(tn.Text);
}
}

您在内部覆盖了 OnItemClicked 方法,当您单击特定的菜单项时,该方法将显示 MessageBox。

因此,当您用鼠标右键单击 treeView 项目时,它将从您的鼠标指针下方检索节点并将其传递给您的 myContextMenuStrip。

    private void treeView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
TreeNode tn = treeView1.GetNodeAt(e.Location);
myMenu.tn = tn;
}
}

在 formLoad 上,您正在初始化 myContextMenuStrip、添加项目并将其绑定(bind)到 treeView。

    private void Form1_Load(object sender, EventArgs e)
{
myMenu = new myContextMenuStrip();
myMenu.Items.Add("asd");
treeView1.ContextMenuStrip = myMenu;
}

我知道这不是很优雅的方式,但它很简单并且有效(与在 EventArgs 中传递 treeNode 值的想法相反,这可能难以实现甚至不可能 - 我自己没有尝试过,尝试过几次但辞职了) .

完整的工作代码,需要表单上的 treeView:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

public myContextMenuStrip myMenu;

private void treeView1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
TreeNode tn = treeView1.GetNodeAt(e.Location);
myMenu.tn = tn;
}
}

private void Form1_Load(object sender, EventArgs e)
{
myMenu = new myContextMenuStrip();
myMenu.Items.Add("asd");
treeView1.ContextMenuStrip = myMenu;
}

public class myContextMenuStrip : ContextMenuStrip
{
public TreeNode tn;

public myContextMenuStrip() { }

protected override void OnItemClicked(ToolStripItemClickedEventArgs e)
{
base.OnItemClicked(e);
if (e.ClickedItem.Text == "asd") MessageBox.Show(tn.Text);
}
}
}
}

关于c# - 从上下文菜单项事件处理程序获取树节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14012950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com