WPF:从ContextMenu中删除TreeViewItem

时间:2010-12-30 06:06:52

标签: wpf tree contextmenu

我正在尝试删除我能够在选择中执行的TreeviewItem。 我想在 ContextMenu 中进行选择时做同样的事情 下面是我创建树和上下文菜单的代码。请提出解决方法。

XAML:

 <TreeView Name="treeFileSystem"  TreeViewItem.Selected="TreeViewItemSelected" >
    <TreeViewItem Header="Suite"  Name="MYTree" Tag="hi"  IsExpanded="True">
               <TreeViewItem    Name="treeFileSystem1" />                       
    </TreeViewItem>
 </TreeView>

CODE:

   private void TestsTreeViewPageFunction_Loaded(object sender,RoutedEventArgs e)
        {
            this.MYTree.Items.Clear();
            this.MYTree.ContextMenu = AddContexMenu("Suite");
            for (int j = 1; j < 5; j++)
            {   TreeViewItem Case = new TreeViewItem();
                Case.ContextMenu = AddContexMenu("Case");
                Case.Header = "Case "+j.ToString();
                Case.IsExpanded = true;
                this.MYTree.Items.Add(Case);
            }
        }

     private ContextMenu AddContexMenu(string var)
        {            
            ContextMenu menu = new ContextMenu();
            MenuItem obj1 = new MenuItem();
            obj1.Click += delegate(System.Object o, RoutedEventArgs e)
            {
                    **?????????????**        
            };
            obj1.Header = "Delete " + var;
            menu.Items.Add(obj1);
            return menu;
        }

        private void TreeViewItemSelected(object sender, RoutedEventArgs e)
        {
           TreeViewItem TreeItem = (TreeViewItem)e.OriginalSource;
           TreeViewItem Parent = (TreeViewItem)TreeItem.Parent;
           Parent.Items.Remove(TreeItem);
        }

1 个答案:

答案 0 :(得分:1)

我找到了解决问题的方法。

以下是解决方案。

 obj1.Click += delegate(System.Object o, RoutedEventArgs e)

  {

       MenuItem menuObject = (MenuItem)o;

TreeViewItem menutreeItem =((ContextMenu)menuObject.Parent).PlacementTarget as 

TreeViewItem;

//To get the Tree from which the context menu is called  

 TreeViewItem Parent = (TreeViewItem)menutreeItem.Parent;

//To get the parent of the TreeViewItem  

 Parent.Items.Remove(menutreeItem); 

//Removing the TreeItem from Parent 


 };