2011-01-13 54 views
3

我有一個ListView控件的DataTemplate。這個DataTemplate位於Templates.xaml(這是一個ResourceDictionary)。然後通過ResourceDictionary.MergedDictionaries將Template.xaml包含到我的主UserControl SourceManager.xaml中。我想提高DataTemplate的ListView的SelectionChanged事件,但我希望後臺代碼中的處理程序位於SourceManager.xaml.cs中。WPF:如何處理單獨文件中的DataTemplate中的事件?

我該如何做到這一點?

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 [email protected]}" /> 
     <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 [email protected]}" 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> 

回答

0

由於SelectionChangedRoutedEvent,你可以將它應用到您的UserControl像這樣:

<UserControl ... 
      ListView.SelectionChanged="MyEventHandler" /> 

請注意,此事件處理程序將被調用所有Selector派生類(如Selector是該事件的定義,並提出)是你的UserControl,其中包括ComboBoxMenuListBox的後裔,等

+0

感謝您的回覆,但是這個解決方案似乎有點混亂,因爲所有的選擇器派生類都會觸發這個處理器。有另一種方法嗎? – Mike 2011-01-13 20:17:30

+0

您可以將代碼隱藏添加到您的ResourceDictionary中,並像在Us​​erControl中那樣添加事件處理程序。如果你這樣做,事件處理程序將在ResourceDictionary的代碼隱藏中被調用,而不是在你的UserControl中。 – 2011-01-13 20:24:06

-1

創建行爲

將其放在數據模板中。

就是這樣。

相關問題