右键单击添加上下文菜单。

时间:2014-06-03 05:39:52

标签: c# wpf treeview contextmenu right-click

public void mytree()
{
    DatabaseCore db = new DatabaseCore();

    List<allTreeView> myList = new List<allTreeView>();

    DataTable dt = db.FillDataGrid();
    foreach (DataRow row in dt.Rows)
    {
        string categories_id1 = row["ID"].ToString();
        string parent_id = row["parentId"].ToString();
        string categories_name = row["name"].ToString();
        myList.Add(new allTreeView(
                    int.Parse(categories_id1), 
                    categories_name, 
                    int.Parse(parent_id)));
    }
    Dictionary<int, TreeViewItem> flattenedTree = 
        new Dictionary<int, TreeViewItem>();

    foreach (allTreeView item in myList)
    {

        TreeViewItem treeNode = new TreeViewItem();
        treeNode.Header = item.Header;              //this is header
        treeNode.Tag = item;
        flattenedTree.Add(item.ID, treeNode);
        if (flattenedTree.ContainsKey(item.ParentID))
        {
            flattenedTree[item.ParentID].Items.Add(treeNode);
        }
        else
        {
            product_tree.Items.Add(treeNode);
        }
    }
}

这会填充我的树。 我想在右键单击上显示上下文菜单,以便在我的树的每个节点上复制,剪切,选择和添加更多功能。

1 个答案:

答案 0 :(得分:3)

在xaml中创建Treeview并使用绑定来填充树。它更容易。

然后你可以这样做:

<TreeView Name="MyTreeview" .........>

 <TreeView.ContextMenu x:Uid="cxt">                            
      <ContextMenu Name="ContextMenu">                                          
       <MenuItem Name="AddNew" Header="Add" Click="AddNew_Click"></MenuItem>
      <Separator/>
      <MenuItem Name="CopyItem" Header="Copy(Ctrl + C)"  Click="CopyItemy_Click"> </MenuItem>

       </ContextMenu>
 </TreeView.ContextMenu>

 ......

</TreeView>