Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 639
Rachel Avatar asked Jul 23 '10 19:07

Rachel


1 Answers

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

like image 120
Thomas Levesque Avatar answered Oct 17 '22 20:10

Thomas Levesque