Attaching events to Silverlight's DataTemplate
If you've used DataTemplates in Silverlight 2, you've noticed that when defining it in a resource of a control, the attached event should be placed in the .cs file containing that control.
If it's a UserControl, it is logical for it to be in the usercontrol's .cs file, usually either coding for that event in the user control itself or exposing the event as an event exposed by the user control.
So far so good, but what happens if we have a general DataTemplate that is used in multiple control / user controls / pages ... ? the obvious answer is place it the app.xaml, but what will happen if we want to catch events from the contained controls in the DataTemplate? putting the event code in the app.xaml.cs is the only way to do it, but it isn't logical to put event code in the app.xaml.cs which will refer to a usercontro/page, isn't it so?
One way we can solve this problem is to define the DataTemplate in a new user control, wrap the event with a new event of the usercontrol's raise that event accordingly.
If you choose to create a UserControl for every DataTemplate or create a “Templates” UserControl for all DataTemplates that have a common usage, it's up to you.
I've attached an example demonstrating this