Binding a TreeView with ContextMenu in Xaml
- by Michael Stoll
I'm pretty new to Xaml and need some advise.
A TreeView should be bound to a hierarchical object structure. The TreeView should have a context menu, which is specific for each object type.
I've tried the following:
<TreeView>
<TreeView.Resources>
<DataTemplate x:Key="RoomTemplate">
<TreeViewItem Header="{Binding Name}">
<TreeViewItem.ContextMenu>
<ContextMenu>
<MenuItem Header="Open" />
<MenuItem Header="Remove" />
</ContextMenu>
</TreeViewItem.ContextMenu>
</TreeViewItem>
</DataTemplate>
</TreeView.Resources>
<TreeViewItem Header="{Binding Name}" Name="tviRoot" IsExpanded="True" >
<TreeViewItem Header="Rooms"
ItemsSource="{Binding Rooms}"
ItemTemplate="{StaticResource RoomTemplate}">
<TreeViewItem.ContextMenu>
<ContextMenu>
<MenuItem Header="Add room"></MenuItem>
</ContextMenu>
</TreeViewItem.ContextMenu>
</TreeViewItem>
</TreeViewItem>
But with this markup the behavior is as intended, but the child items (the rooms) are indented too much.
Anyway all the bining samples I could find use TextBlock instead of TreeViewItem in the DataTemplate, but wonder how to integrate the ContextMenu there.