C# – How to display context menu for treeview item in a hierarchial data template in wpf

c++, contextmenu, treeview, wpf

How to display context menu for tree view item in wpf using the hierarchical data template? How to display context menu only for CountryTemplate:

  <HierarchicalDataTemplate  x:Key="DispTemplate">        <StackPanel Orientation="Horizontal">            <TextBlock Text="{Binding Path=Label}" Style="{StaticResource TreeTextStyle}" ToolTip="{Binding Path=Description}" Tag="{Binding Path=Tag}">            </TextBlock>        </StackPanel>    </HierarchicalDataTemplate>    <HierarchicalDataTemplate  x:Key="BuildingTemplate"  ItemsSource="{Binding Path=Building}" ItemTemplate="{StaticResource BuildingTemplate}">        <StackPanel Orientation="Horizontal">            <TextBlock Text="{Binding Path=Label}" Style="{StaticResource TreeTextStyle}" ToolTip="{Binding Path=Description}"/>        </StackPanel>    </HierarchicalDataTemplate>    <HierarchicalDataTemplate  x:Key="CityTemplate"  ItemsSource="{Binding Path=City}" ItemTemplate="{StaticResource CityTemplate}">        <StackPanel Orientation="Horizontal">            <TextBlock Text="{Binding Path=Label}" Style="{StaticResource TreeTextStyle}" ToolTip="{Binding Path=Description}"/>        </StackPanel>    </HierarchicalDataTemplate>    <HierarchicalDataTemplate x:Key="CountryTemplate" ItemsSource="{Binding Path=Country}" ItemTemplate="{StaticResource CountryTemplate}">        <StackPanel Orientation="Horizontal">            <TextBlock Text="{Binding Path=RootName}" Style="{StaticResource TreeTextStyle}" ToolTip="{Binding Path=Description}"/>        </StackPanel>    </HierarchicalDataTemplate>

Best Solution

You also can add the ContextMenu to any visual child in the data template, for instance:

<HierarchicalDataTemplate x:Key="CountryTemplate" ItemsSource="{Binding Path=Country}" ItemTemplate="{StaticResource CountryTemplate}">    <StackPanel Orientation="Horizontal">        <StackPanel.ContextMenu>            <ContextMenu>                 <MenuItem Header="Header" Command="{Binding Command}"/> <!--This command should be in the data context (each country item)-->            </ContextMenu>        </StackPanel.ContextMenu>        <TextBlock Text="{Binding Path=RootName}" Style="{StaticResource TreeTextStyle}" ToolTip="{Binding Path=Description}"/>    </StackPanel></HierarchicalDataTemplate>