Reputation: 23
I am trying to build a custom control which has button and text. When i am trying to compile i am getting the following error.
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.
My Code :
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:textbtn">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<TextBlock Text="This is a Test" Foreground="Aqua" Background="AntiqueWhite"/>
<Button Content="Button" Height="23" HorizontalAlignment="bottom" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Upvotes: 1
Views: 798
Reputation: 1632
The error is well explained by LordTakkera, but he doesn't want the simple solution to be appened to his answer, so, to clear the point, Providing a Class Name to the resource dictionary will allow you to use event handler as in other controls:
<ResourceDictionary
x:Class="ResourceDictionaryClass1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:textbtn">
But indeed is LordTakkera right: Commands are a clean way of implementing ui callbacks.
Upvotes: 2
Reputation: 61339
The error means exactly what it says. The click event handler actually does the following:
myButtonName.Click += myClass.ClickHandlerName;
If you don't have a class assigned to the resource dictionary, it doesn't know what to assign the click handler to!
Because a control template shouldn't be tightly coupled to a specific class in the code behind, I would remove the click handler from the template entirely. Command is a better choice in MVVM anyways.
Upvotes: 3