TreeViewItems和ContextMenu

时间:2013-07-03 13:23:15

标签: c# wpf events

我为特定的TreeViewItem指定ContextMenu有一点问题:

    <TreeView x:Name="_filesTree">
    <TreeView.Resources>
        <ContextMenu x:Key="_rootContextMenu">
            <MenuItem Header="Add..." Click="MenuItem_Click" />
        </ContextMenu>
    </TreeView.Resources>
    <TreeViewItem Header="Persistent" ContextMenu="{DynamicResource _rootContextMenu}"/>
    <TreeViewItem Header="Temporary" ContextMenu="{DynamicResource _rootContextMenu}" />
</TreeView>

点击处理程序:

        private void MenuItem_Click(object sender, RoutedEventArgs e)
    {
        Point menuClickPoint = ((sender as FrameworkElement).Parent as ContextMenu).TranslatePoint(new Point(0, 0), _filesTree);
        DependencyObject obj = _filesTree.InputHitTest(menuClickPoint) as DependencyObject;

        while (obj != null && !(obj is TreeViewItem))
        {
            obj = VisualTreeHelper.GetParent(obj);
        }

        (obj as TreeViewItem).Items.Add("(new)");
    }

在我的* MenuItem_Click *事件处理程序中,我将新的TreeViewItem添加到单击的项目,什么工作正常。但在添加新的(例如“持久”子树)后,右键单击此新子项将再次打开上下文菜单。这是我不需要的东西,因为我需要为这些新添加的项目提供另一个上下文菜单(使用Remove选项)。 只有在右键单击根项(TextBlock)而不是在子树内时才能打开如何获取上下文菜单?

谢谢

1 个答案:

答案 0 :(得分:0)

我为每个子项明确定义了新的上下文菜单:

        TreeViewItem tvi = new TreeViewItem();
        tvi.ContextMenu =(ContextMenu) this._filesTree.Resources["_subItemContextMenu"];
        tvi.Header = "(new)";

        (obj as TreeViewItem).Items.Add(tvi);
树视图资源中的

* _ subItemContextMenu *:

<ContextMenu x:Key="_subItemContextMenu">
        <MenuItem Header="Remove" Click="MenuItem_Remove" />
</ContextMenu>