I think it will be very hard for you to read the code but I’ll try to do my best !
Here is my xaml code :
<TreeView x:Name="stateMachinesView"
DockPanel.Dock="Top"
SelectedItemChanged="item_Selected"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
BorderThickness="0">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Value}">
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<DockPanel>
<DockPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="Create Thumbnail"
Click="MenuItemCreate_Click"/>
</ContextMenu>
</DockPanel.ContextMenu>
<Image>
<Image.Style>
<Style TargetType="Image">
<Style.Setters>
<Setter Property="Source"
Value="Resources\state.png"/>
</Style.Setters>
<Style.Triggers>
<DataTrigger Binding="{Binding Item2}"
Value="true">
<Setter Property="Source"
Value="Resources\state_init.png"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<TextBlock>
<TextBlock.Text>
<Binding Path="Item1"/>
</TextBlock.Text>
</TextBlock>
</DockPanel>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
<DockPanel>
<Image DockPanel.Dock="Left"
Source="Resources\state_machine.png"/>
<TextBlock Text="{Binding Key}"/>
</DockPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
The item source of this is a Dictionary<string, ObservableCollection<Tuple<string, bool>>>
Visually, I got something like this:

Now, when I click on my MenuItem I got this code:
private void MenuItemCreate_Click(object sender, RoutedEventArgs e)
{
string stateName =
((sender as FrameworkElement).DataContext as Tuple<string, bool>).Item1;
}
Here I can access to State1_1 with the code above, but now I would like to access to SM1 the parent node !
I tried a lot of things, the closest (to the solution) was this:
DependencyObject parent = VisualTreeHelper.GetParent(sender as DependencyObject);
while (!(parent is TreeViewItem))
parent = VisualTreeHelper.GetParent(parent);
But it doesn’t work…
I am, too, thinking about a Template in XAML but im sure I can do it in the code-behind easily!
ContextMenusare not on the same visual tree as the object they are used on. You have go up twiceContextMenu, there you can get theTreeViewItemfrom theContextMenu.PlacementTarget.TreeViewItem.Of course it would be easier if you just have a reference to the parent in the data items themselves. Also you should not need to acces the
TreeViewItemsas you usually bind everything as necessarry.