【发布时间】:2018-05-09 19:05:40
【问题描述】:
2018 年 5 月 10 日更新。 orhtej2 建议我的问题可能是Determine what control the ContextMenuStrip was used on 的重复。这是几乎重复,但我的情况有一个显着的差异。有关详细信息,请参阅我修改后的问题和答案。
请参阅下面的代码。我的目标是更清楚地确定哪个 TreeNode 在其 ContextMenuItems 之一被左键单击后被右键单击。
就像现在一样,当我右键单击两个子节点之一时,TreeView1_NodeMouseClick 中的 if 语句会将单击的 TreeNode 加载到全局 treeViewClickedNode TreeNode 对象中。然后,当我左键单击两个contextMenuStripChildNode ToolStripMenuItem 之一时,DocumentActionToolStripMenuItem_CheckStateChanged 方法被触发。然后我可以检查检查状态。如果选中,我可以对 treeViewClickedNode TreeNode 做点什么。
我的问题:有没有一种更简洁的方法来确定在其 ContextMenuStrip 项目之一被左键单击后右键单击哪个 TreeNode,即,有没有办法取消全局变量 treeViewClickedNode?
注意:我在设计器中所做的唯一事情是将treeview1 放在Form1 上,将其停靠到Form1 并将'treeview1' NodeMouseClick 设置为TreeView1_NodeMouseClick
using System;
using System.Windows.Forms;
namespace WindowsFormsApp_Scratch
{
public partial class Form1 : Form
{
TreeNode treeViewClickedNode;
ContextMenu mnu = new ContextMenu();
public Form1()
{
InitializeComponent();
// Create the root node.
TreeNode treeNodeRoot = new TreeNode("Documents");
// Add the root node to the TreeView.
treeView1.Nodes.Add(treeNodeRoot);
//Create and add child 2 nodes each with a two item ContextMenuStrip.
string[] childNodeLabels = { "document1.docx", "document2.docx"};
string[] contextItemLabels = { "Action A", "Action B" };
foreach (String childNodeLabel in childNodeLabels)
{
TreeNode treeNode = treeNodeRoot.Nodes.Add(childNodeLabel);
// Create a ContextMenuStrip for this child node.
ContextMenuStrip contextMenuStripChildNode = new ContextMenuStrip
{
ShowCheckMargin = true,
ShowImageMargin = false
};
foreach (String contextItemLabel in contextItemLabels)
{
//Create a menu item.
ToolStripMenuItem action = new ToolStripMenuItem(contextItemLabel, null, DocumentActionToolStripMenuItem_CheckStateChanged)
{
CheckOnClick = true
};
contextMenuStripChildNode.Items.Add(action);
}
treeNode.ContextMenuStrip = contextMenuStripChildNode;
}
private void TreeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeView t = (TreeView)sender;
//Force the node that was right-clicked to be selected
t.SelectedNode = t.GetNodeAt(e.X, e.Y);
if (e.Button == MouseButtons.Right)
{
treeViewClickedNode = e.Node;
}
}
private void DocumentActionToolStripMenuItem_CheckStateChanged(object sender, EventArgs e)
{
ToolStripMenuItem toolStripMenuItem = (ToolStripMenuItem)sender;
if (toolStripMenuItem.CheckState == CheckState.Checked)
{
//Do something with treeViewClickedNode object
}
}
}
}
【问题讨论】:
-
@orhtej2:几乎是个骗子。查看我对问题和答案所做的更改(基于 S.O. 问题Determine what control the ContextMenuStrip was used on
标签: c# winforms treeview contextmenustrip toolstripmenu