I'm trying to add a contextmenu along with a contextmenuitem and a handler in a template file. The former things are fine but VS won't let me add a eventhandler to the menuitem in the template file, it looks like so
<ControlTemplate TargetType="{x:Type local:CalendarDayView}">
<ControlTemplate.Resources>
<ContextMenu x:Key="dayEntryContextMenu">
<MenuItem Header="Remove entry" Click="removeEntryBtn"/>
</ContextMenu>
</ControlTemplate.Resources>
<Border BorderBrush="Gray" BorderThickness="1" Width="100" Height="100">
<Grid Name="contentGrid">
<ListBox Name="entriesListBox" Background="LightYellow" ContextMenu="{StaticResource dayEntryContextMenu}">
<ListBoxItem>Test entry #1</ListBoxItem>
<ListBoxItem>Test entry #2</ListBoxItem>
<ListBoxItem>Test entry #3</ListBoxItem>
</ListBox>
<!-- Date display below -->
<TextBlock Name="dateTextBlock" Text="31-Nov" FontFamily="Segoe UI Light" FontSize="18" VerticalAlignment="Bottom" HorizontalAlignment="Right"/>
</Grid>
</Border>
</ControlTemplate>
The error I'm getting is Error 1 'ResourceDictionary' root element requires a x:Class attribute to support event handlers in the XAML file. Either remove the event handler for the Click event, or add a x:Class attribute to the root element. Line 37 Position 61.
Is there any way to make this work?
The problem is that your event handler needs to be implemented in a code behind file, but since you only have your xaml file without any *.cs file behind it, VS does not know where your event handler should be implemented.
To fix this you need to add a code-behind file for your xaml file. In that code behind file, you have to define the class of your resourcedictionary (where your ControlTemplate is stored) and then you can define the "x:class" attribute in your xaml file. After that, you should be able to define your event handler.
See a more complete description here.