views:

47

answers:

1

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.

+1  A: 

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

Thomas Levesque
That is what I currently have... A class for the ResourceDictionary with it's Build Action set to Page. Only difference I can see is I didn't declare it public, but changing that didn't help at all.
Rachel
And what's the problem exactly ? Do you get an error message ?
Thomas Levesque
When I go to run the program, it throws a NullReferenceException (it compiles fine). It must have something to do with my design pattern because I tried creating a simple test case and its working fine. My main app overwrites app.xaml's OnStartup to load a bunch of different ResourceDictionaries, creates an instance of MainWindow, sets its DataContext, then calls MainWindow.Show() - The last line is where I'm getting the exception. Moving the Event from the ControlTemplate to an EventSetter gets rid of the error.
Rachel
The ResourceDictionary I am testing with defines a DataTemplate for a custom object, and in that DataTemplate there is a custom UserControl. The UserControl.Resources contains the ControlTemplate containing the event, and the UserControl.Content contains a ContentControl that references the ControlTemplate.
Rachel
Then you need to take the ControlTemplate to an other file
Thomas Levesque
Why is that? I was hoping to avoid that because sections of the application are modular and I wanted to keep all the resources for a section together in one file.
Rachel