WPF: TreeViewItem deletion from ContextMenu
I am trying to delete TreeviewItem which I am able to do it on Selection. The same thing I want to do it on selection from ContextMenu. Below is my code for creation of Tree and context Menu. Please suggest way to solve.
XAM开发者_开发问答L:
<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);
}
I have found a way to solve my problem.
Below is the solution.
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
};
精彩评论