Search code examples
wpfcontroltemplaterouted-events

WPF - Events on a ControlTemplate?


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.


Solution

  • 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...)