Mizipzor
Mizipzor

Reputation: 52351

How to handle events inside a WPF DataTemplate?

I have a custom control which has a dependency property called ViewModel which value is shown inside a ContentPresenter. I have a DataTemplate for each type of ViewModel. Each template allows the user to make a selection in a different way and I need to handle that selection event in the custom control code behind.

<Style TargetType="{x:Type local:MyCustomControl}">

    <Style.Resources>
        <ResourceDictionary>

            <DataTemplate DataType="{x:Type local:ViewModelOne}">

                <!-- how to handle this event? -->
                <ListBox
                    MouseDoubleClick="ListBox_MouseDoubleClick"/>
            </DataTemplate>

            <DataTemplate DataType="{x:Type local:ViewModelTwo}">

                <!-- this ListBox has another style, but event should
                     be handled the same way -->
                <ListBox
                    MouseDoubleClick="ListBox_MouseDoubleClick"/>
            </DataTemplate>

            <!-- more templates here -->

        </ResourceDictionary>
    </Style.Resources>

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyCustomControl}">
                <ContentPresenter Content="{TemplateBinding ViewModel}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Edit:

Here's the code behind of the custom control with the method I would like to be called when something in the ListBox is double clicked:

public class MyCustomControl : Control
{
    // how to attach ListBox MouseDoubleClick event to this method? 
    private void ListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        DoMagic(((ListBox)sender).SelectedItem);
    }
}

Upvotes: 3

Views: 4626

Answers (1)

Vinit Sankhe
Vinit Sankhe

Reputation: 19885

Are these DataTemplates defined in a resource dictionary?

if so, you can use the attached behaviors.

If they are defined in a MyWindow or a MyUserControl XAML then you can defined them the code behind i.e. MyWindow.xaml.cs or MyUserControl.xaml.cs

Upvotes: 1

Related Questions