1 把MenuStrip内容复制到一个TreeView ,这样调用即可:CopyMenuToTree(menuStrip1, treeView1);
2
3 private void CopyMenuToTree(MenuStrip menu,TreeView tree)
4 {
5 foreach (ToolStripMenuItem item in menu.Items)
6 {
7 TreeNode node = new TreeNode(item.Text);
8 tree.Nodes.Add(node);
9 Copy(item,node);
10 }
11 }
12 private void Copy(ToolStripMenuItem item, TreeNode node)
13 {
14 foreach (ToolStripMenuItem subItem in item.DropDownItems)
15 {
16 TreeNode subNode = new TreeNode(subItem.Text);
17 node.Nodes.Add(subNode);
18 Copy(subItem, subNode);
19 }
20 }
简化的版本,一样的效果,调用 CopyMenuToTree(menuStrip1.Items, treeView1.Nodes);
private void CopyMenuToTree(ToolStripItemCollection itemColl,TreeNodeCollection nodeColl)
{
foreach (ToolStripMenuItem item in itemColl)
{
TreeNode node = new TreeNode(item.Text);
nodeColl.Add(node);
CopyMenuToTree(item.DropDownItems, node.Nodes);
}
}
treeview上面的节点,点击能不能与menustrip同步
CopyMenuToTree(menuStrip1.Items, treeView1.Nodes);
private void CopyMenuToTree(ToolStripItemCollection itemColl,TreeNodeCollection nodeColl)
{
foreach (ToolStripMenuItem item in itemColl)
{
TreeNode node = new TreeNode(item.Text);
node.Tag = item; //增加这个哦《=====================================
nodeColl.Add(node);
CopyMenuToTree(item.DropDownItems, node.Nodes);
}
}
设置TreeView的AfterSelect事件
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
ToolStripMenuItem item = e.Node.Tag as ToolStripMenuItem;
item.PerformClick();
}