WPF - Events on a ControlTemplate?

Rachel picture Rachel · Jul 23, 2010 · Viewed 8.6k times · Source

Does anyone know why I can't set an event on a control template??

For example, the following line of code will not compile. It does this with any events in a control template.

<ControlTemplate x:Key="DefaultTemplate" TargetType="ContentControl">
   <StackPanel Loaded="StackPanel_Loaded">

   </StackPanel>
</ControlTemplate>

I am using a MVVM design pattern and the control here is located in a ResourceDictionary that is added to the application's MergedDictionaries.

Answer

Thomas Levesque picture Thomas Levesque · Jul 23, 2010

Does anyone know why I can't set an event on a control template??

Actually, you can... But where would you expect the event handler to be defined ? The ResourceDictionary has no code-behind, so there is no place to put the event handler code. You can, however, create a class for your resource dictionary, and associate it with the x:Class attribute :

<ResourceDictionary x:Class="MyNamespace.MyClass"
                    xmlns=...>

    <ControlTemplate x:Key="DefaultTemplate" TargetType="ContentControl">
       <StackPanel Loaded="StackPanel_Loaded">

       </StackPanel>
    </ControlTemplate>

C# code :

namespace MyNamespace
{
    public partial class MyClass : ResourceDictionary
    {
        void StackPanel_Loaded(object sender, RoutedEventArgs e)
        {
            ...
        }
    }
}

(you might also need to change the build action of the resource dictionary to "Page", I don't remember exactly...)