I am inserting TreeViewItems into a TreeView control and setting the style for each at the time of insertion. I am assigning different styles (predefined in XAML), depending on the type of node (TreeViewItem) I want to insert. Some of the styles include a ContextMenu.
My problem is that I am unable to use Click="MyHandler" on the MenuItems; I get an error "root element requires a x:Class attribute to support event handlers in the XAML file." and apparently none of the elements within the Style block are root elements.
Any suggestions much appreciated.
XAML:
<Style x:Key="Terrain" TargetType="{x:Type TreeViewItem}">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Canvas Background="{DynamicResource Terrain_icon}" />
<TextBlock Text="{Binding}" />
<StackPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="Edit..." Click="MyHandler"/> <!-- Error -->
<MenuItem Header="Add..."/>
<MenuItem Header="Delete"/>
</ContextMenu>
</StackPanel.ContextMenu>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
C#:
private void InsertTerrainNode(object sender, System.Windows.RoutedEventArgs e)
{
// Add the new item under the first-level TreeViewItem
TreeViewItem tvi = myTree.ItemContainerGenerator.ContainerFromItem(myTree.Items[0]) as TreeViewItem;
TreeViewItem newTerrainNode = new TreeViewItem();
newTerrainNode.Header = "Terrain";
newTerrainNode.Style = (Style)this.FindResource("Terrain");
tvi.Items.Insert(0,newTerrainNode);
}