WPF how to change contextmenu items based on treeviewitem type?

c#, contextmenu, treeview, wpf, xaml

Solution

I'm assuming you are binding your `TreeView` to a list of items. If so, are or can the first and second tier of items be of different data types? Then, you can do a `HierarchicalDataTemplate` for your first tier type and a `DataTemplate` for your second tier type as such:

<HierarchicalDataTemplate DataType="{x:Type local:FirstTierType}" ItemsSource="{Binding Items}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}"  />
    </StackPanel>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:SecondTierType}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}"  />
        <StackPanel.ContextMenu>
            <ContextMenu>
               <MenuItem Header="whatever1" Command="whatever1cmd"></MenuItem>
               <MenuItem Header="whatever2" Command="whatever2cmd"></MenuItem>
               <MenuItem Header="whatever3" Command="whatever2cmd"></MenuItem>
            </ContextMenu>
        </StackPanel.ContextMenu>
    </StackPanel>
</DataTemplate>
.
.
.
<TreeView ItemsSource="{Binding Items}" />

Problem

I have a `TreeView` of items and I want a `ContextMenu` to pop up only for the second tier items. How do I go about doing that?

Original source