WPF: How to handle events in a DataTemplate that are in a separate file?

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

How can i achieve this?

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>
+3
source share
2 answers

Since it SelectionChangedis RoutedEvent, you can apply it to yours UserControllike this:

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

, Selector ( Selector ), UserControl, ComboBox, Menu, ListBox ..

0

.

.

-1

Source: https://habr.com/ru/post/1785265/


All Articles