<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<EventSetter Event="TreeViewItem.PreviewMouseRightButtonDown" Handler="TreeViewItem_PreviewMouseRightButtonDown"/>
</Style>
</TreeView.ItemContainerStyle>
private void TreeViewItem_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
var treeViewItem = VisualUpwardSearch<TreeViewItem>(e.OriginalSource as DependencyObject) as TreeViewItem;
if (treeViewItem != null)
{
treeViewItem.Focus();
e.Handled = true;
CreateContextMenu(treeViewItem);
}
}
static DependencyObject VisualUpwardSearch<T>(DependencyObject source)
{
while (source != null && source.GetType() != typeof(T))
source = VisualTreeHelper.GetParent(source);
return source;
}
private void CreateContextMenu(TreeViewItem item)
{
ContextMenu contextMenu = new ContextMenu();
MenuItem menuAddItem = new MenuItem();
menuAddItem.Header = "添加";
menuAddItem.Click += (sender, e) =>
{
item.IsSelected = true;
txtInput = new TextBoxInput();
txtInput.Show();
txtInput.SetTreeViewItem(CustomTreeView, item, 1);//自己的业务代码
};
contextMenu.Items.Add(menuAddItem);
MenuItem menuEditItem = new MenuItem();
menuEditItem.Header = "修改";
menuEditItem.Click += (sender, e) =>
{
item.IsSelected = true;
txtInput = new TextBoxInput();
txtInput.Show();
txtInput.SetTreeViewItem(CustomTreeView, item, 2);//自己的业务代码
};
contextMenu.Items.Add(menuEditItem);
MenuItem menuDelItem = new MenuItem();
menuDelItem.Header = "删除";
menuDelItem.Click += (sender, e) =>
{
if (item != null)
{
DeleteNode(item);//自己的业务代码
}
};
contextMenu.Items.Add(menuDelItem);
this.CustomTreeView.ContextMenu = contextMenu;
}