我有一个WPF TreeView,一些TreeViewItems有一个上下文菜单。例如, 根节点2没有上下文菜单,但节点1没有。加载窗口后,当我第一次右键单击节点2或Root时,我没有看到上下文菜单,单击节点1时,显示上下文菜单,到目前为止还不错。现在,当我点击节点2时,我看到一个上下文菜单,但我没有将任何上下文菜单分配给'Node 2'treeviewitem。
事件:
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Setter Property="IsExpanded" Value="True" />
<EventSetter Event="PreviewMouseRightButtonDown" Handler="OnPreviewMouseRightButtonDown" />
</Style>
</TreeView.ItemContainerStyle>
事件处理程序:
private void OnPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
var obj = e.OriginalSource as DependencyObject;
var item = GetDependencyObjectFromVisualTree(obj, typeof(TreeViewItem)) as TreeViewItem;
if (item == null) return;
item.Focus();
item.IsSelected = true;
var selectedElement = (XmlElement)item.Header;
string type = selectedElement.GetAttribute("Type");
if (type.ToLower().Trim() == "Node 1")
{
var menuitem1 = new MenuItem(); menuitem1.Header = "New..."; menuitem1.Width = Double.NaN;
var menuitem2 = new MenuItem(); menuitem2.Header = "Open...";
var menu = new ContextMenu() { };
menu.Items.Add(menuitem1);
menu.Items.Add(menuitem2);
(sender as TreeViewItem).ContextMenu = menu;
}
else
{
(sender as TreeViewItem).ContextMenu = null;
}
e.Handled = true;
}
我尝试将Null分配给上下文菜单,但没有用。当我调试时,我可以看到没有为TreeViewItem分配上下文菜单,但即使这样也会显示。