树视图项焦点阻止显示上下文菜单

本文关键字:显示 上下文 菜单 视图 焦点 | 更新日期: 2023-09-27 17:57:01

我目前正在尝试将焦点设置在我的树视图的选定值上,然后显示代码隐藏中内置的上下文菜单。

上下文菜单的焦点和显示都可以单独工作,但是当我在同一块中同时具有两者时,只有焦点触发而上下文菜单不显示?

我想找出为什么我的树视图项焦点阻止显示上下文菜单。

这是我的点击事件

private void TextBlock_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
        //searches up the tree until it finds the first treeviewitem and sets the focus to it.
        TreeViewItem treeViewItem = VisualUpwardSearch(e.OriginalSource as DependencyObject);
        if (treeViewItem != null)
        {
            treeViewItem.Focus();
            e.Handled = true;
        }
        tvProjects.Tag = treeViewItem.Header;


        var fm = new FileMenu();
        var m = new MainViewModel();
        //Create new contextmenu and set datacontext and itemsource
        ContextMenu cm = new ContextMenu();
        cm.DataContext = m;
        cm.ItemsSource = m.MenuItems;
        //set bindings through style
        Style style = new Style();
        style.TargetType = typeof(MenuItem);
        style.Setters.Add(new Setter(MenuItem.HeaderProperty, new Binding("Header")));
        style.Setters.Add(new Setter(MenuItem.ItemsSourceProperty, new Binding("Items")));
        style.Setters.Add(new Setter(MenuItem.CommandProperty, new Binding("Command")));
        style.Setters.Add(new Setter(MenuItem.CommandParameterProperty, new Binding("CommandParameter")));
        cm.ItemContainerStyle = style;
        TextBlock tb = (TextBlock)sender;
        //Show the menu
        tb.ContextMenu = cm;
        tb.ContextMenu.Visibility = System.Windows.Visibility.Visible;
    }

树视图项焦点阻止显示上下文菜单

我发现了为什么它没有处理这两个事件,行

e.Handled = true;

阻止了其余代码的执行,因为 MouseButtonEventArgs 已经处理完毕,因此代码不会打扰执行其余代码。

删除上述代码行后,一切正常。