Mike S

Mike S

  • NA
  • 1
  • 11.6k

How do I handle events in a DataTemplate that is in a separate file?

Jan 13 2011 6:15 PM

I have a DataTemplate with a ListView control. This DataTemplate is located in Templates.xaml (which is a ResourceDictionary). Template.xaml is then included into my main UserControl SourceManager.xaml through ResourceDictionary.MergedDictionaries. I want to raise the SelectionChanged event of the DataTemplate's ListView but I want the handler in the code behind to be in SourceManager.xaml.cs.

How can I achieve that?

Templates.xaml:

 <ResourceDictionary x:Class="LawBib.Templates"
         
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<DataTemplate x:Key="SectionTemplate">
   
<StackPanel>
       
<TextBlock Text="{Binding XPath=@Title}" />
       
<ListView x:Name="GroupList" ItemsSource="{Binding XPath=Source}">
           
<ListView.Template>
               
<ControlTemplate>
                   
<WrapPanel IsItemsHost="True">

                   
</WrapPanel>
               
</ControlTemplate>
           
</ListView.Template>
           
<ListView.ItemTemplate>
               
<DataTemplate>
                   
<StackPanel>
                       
<Image Source="images/source.png" />
                       
<TextBlock Text="{Binding XPath=@Title}" HorizontalAlignment="Center" />
                   
</StackPanel>
               
</DataTemplate>
           
</ListView.ItemTemplate>
       
</ListView>
   
</StackPanel>
</DataTemplate>

SourceManager.xaml:

 <UserControl x:Class="LawBib.SourceManager"
             
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             
mc:Ignorable="d"
             
d:DesignHeight="300" d:DesignWidth="300" Background="#f5f7f8">
   
<UserControl.Resources>
       
<ResourceDictionary>
           
<ResourceDictionary.MergedDictionaries>
               
<ResourceDictionary Source="Resources.xaml" />
               
<ResourceDictionary Source="Templates.xaml" />
           
</ResourceDictionary.MergedDictionaries>
       
</ResourceDictionary>
   
</UserControl.Resources>
...
</UserControl>