Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8704801
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T03:12:06+00:00 2026-06-13T03:12:06+00:00

I have the same problem as this question , where I want the TreeViewItem

  • 0

I have the same problem as this question, where I want the TreeViewItem to still look actively selected when its context menu is shown. However, in my tree every level has a different type of object, so I want a different ContextMenu for each level. I’m accomplishing this using the HierachicalDataTemplate. So I have the following XAML:

<Window x:Class="Project.MainWindow">
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Project" ContentRendered="Window_ContentRendered">
    <Grid>
        <Grid.Resources>
            <DataTemplate x:Key="VolumeTemplate">
                <StackPanel Orientation="Horizontal">
                    <Image Source="{StaticResource VolumeIcon}" Margin="3,3,3,3" />
                    <TextBlock Text="{Binding Path=Name}" Margin="3,3,3,3">
                        <TextBlock.ContextMenu>
                            <ContextMenu>
                                <MenuItem Command="{Binding VolumeTestCommand}"
                                          Header="VolumeTest" />
                            </ContextMenu>
                        </TextBlock.ContextMenu>
                    </TextBlock>
                </StackPanel>
            </DataTemplate>
            <HierachicalDataTemplate x:Key="ServerTemplate"
                                     ItemsSource="{Binding Volumes}"
                                     ItemTemplate="{StaticResource VolumeTemplate}">
                <StackPanel Orientation="Horizontal">
                    <Image Source="{StaticResource ServerIcon}" Margin="3,3,3,3" />
                    <TextBlock Text="{Binding Name}" Margin="3,3,3,3" >
                        <TextBlock.ContextMenu>
                            <ContextMenu>
                                <MenuItem Command="{Binding ServerTestCommand}"
                                          Header="ServerTest" />
                            </ContextMenu>
                        </TextBlock.ContextMenu>
                    </TextBlock>
                </StackPanel>
            </HierarchicalDataTemplate>
        </Grid.Resources>
        <TreeView HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                  ItemsSource="{Binding Servers}" Name="tvMain"
                  ItemTemplate="{StaticResource ServerTemplate}"
                  PreviewMouseRightButtonDown="tvMain_PreviewMouseRightButtonDown" />
    </Grid>
</Window>

And code behind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_ContentRendered(object sender, EventArgs e)
    {
        //set DataContext here, based on a login dialog
    }

    static T VisualUpwardSearch<T>(DependencyObject source) where T : DependencyObject
    {
        DependencyObject returnVal = source;

        while (returnVal != null && !(returnVal is T))
        {
            if (returnVal is Visual || returnVal is Visual3D)
            {
                returnVal = VisualTreeHelper.GetParent(returnVal);
            }
            else
            {
                returnVal = LogicalTreeHelper.GetParent(returnVal);
            }
        }

        return returnVal as T;
    }

    private void tvMain_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {
        TreeViewItem treeViewItem = VisualUpwardSearch<TreeViewItem>(e.OriginalSource as DependencyObject);

        if(treeViewItem != null)
        {
            treeViewItem.IsSelected = true;
            e.Handled = true;
        }
    }
}

I tried the answer from the referenced question, but I think it doesn’t work since the context menu is on the TextBlock instead of the TreeViewItem. Is there a way to attach the ContextMenu to the TreeViewItem in the DataTemplate, or another way to address this problem?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T03:12:08+00:00Added an answer on June 13, 2026 at 3:12 am

    I ended up having to create an attached property, which moves the context menu from the TextBlock to the TreeViewItem:

    public static readonly DependencyProperty StealContextMenuProperty = 
        DependencyProperty.RegisterAttached(
            "StealContextMenu", 
            typeof(bool), 
            typeof(ParentClass),
            new UIPropertyMetadata(false, new PropertyChangedCallback(SCMChanged))
        );
    
    public static bool GetStealContextMenu(FrameworkElement obj)
    {
        return (bool)obj.GetValue(StealContextMenuProperty);
    }
    
    public static void SetStealContextMenu(FrameworkElement obj, bool value)
    {
        obj.SetValue(StealContextMenuProperty, value);
    }
    
    public static void SCMChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        FrameworkElement fe = sender as FrameworkElement;
        if (fe == null) return;
    
        bool value = (bool)e.NewValue;
        if (!value) return;
    
        fe.Loaded += new RoutedEventHandler(fe_Loaded);
    }
    
    public static void fe_Loaded(object sender, RoutedEventArgs e)
    {
        FrameworkElement fe = (FrameworkElement)sender;
        FrameworkElement child;
        child = VisualDownwardSearch<FrameworkElement>(fe, x => x.ContextMenu != null);
        if (child != null)
        {
            fe.ContextMenu = child.ContextMenu;
            child.ContextMenu = null;
        }
    }
    
    public static T VisualDownwardSearch<T>(T source, Predicate<T> match)
        where T : DependencyObject
    {
        Queue<DependencyObject> queue = new Queue<DependencyObject>();
        queue.Enqueue(source);
        while(queue.Count > 0)
        {
            DependencyObject dp = queue.Dequeue();
    
            if (dp is Visual || dp is Visual3D)
            {
                int childrenCount = VisualTreeHelper.GetChildrenCount(dp);
                for (int i = 0; i < childrenCount; i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(dp, i);
                    if (child is T)
                    {
                        T tChild = (T)child;
                        if (match(tChild)) return tChild;
                    }
                    queue.Enqueue(child);
                }
            }
            else
            {
                foreach (DependencyObject child in LogicalTreeHelper.GetChildren(dp))
                {
                    if (child is T)
                    {
                        T tChild = (T)child;
                        if (match(tChild)) return tChild;
                    }
                    queue.Enqueue(child);                    
                }
            }
        }
        return null;      
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have basically the same problem outlined in this question, however I am using
I have read the other threads regarding this same problem but I still don't
I have the same problem as the user in this question , which is
I just read this question I have same problem too, but I wanted more.
I have faced the same problem many times. The Same Problem was With This
This is pretty much the same problem i have, except with very different code:
I have this problem when I want to skip to a position while streaming
I have the same problem that is listed in the following thread. WSDL first
I have the same problem as described in ( Last record of Join table
I have the same problem as in the following post . So I am

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.