WPF MVVM - What's the most correct way to fire events within TreeViewItem

2.7k Views Asked by At

I'm currently using this extension to set specific events which handle data in the ViewModel... Example:

<swi:Interaction.Triggers>
    <swi:EventTrigger EventName="Click">
        <esi:CallDataMethod Method="SaveRevision_Clicked"/>
    </swi:EventTrigger>
</swi:Interaction.Triggers>

Where esi and swi are:

xmlns:esi="clr-namespace:Expression.Samples.Interactivity;assembly=Expression.Samples.Interactivity"
xmlns:swi="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

But what I want to set an event for a TreeViewItem? I don't have direct access to them, do I?

EDIT: I'm actually using ItemContainerStyle,

<Style x:Key="FolderView" TargetType="{x:Type TreeViewItem}">
    <Setter Property="HeaderTemplate">
        <Setter.Value>
            <HierarchicalDataTemplate ItemsSource="{Binding Children}"  >
                <StackPanel Orientation="Horizontal">
                    <Image Name="img"
                               Width="20"
                               Height="20"
                               Stretch="UniformToFill"
                               Source="Images/hdicon.png"/>
                    <TextBlock Text="{Binding FolderName}" Margin="5,0" />
                </StackPanel>
            </HierarchicalDataTemplate>
        </Setter.Value>
    </Setter>
</Style>

But I can't place my event in there. Where should I put these lines?

<swi:Interaction.Triggers>
    <swi:EventTrigger EventName="Expanded">
        <esi:CallDataMethod Method="Expand"/>
    </swi:EventTrigger>
</swi:Interaction.Triggers>

Thanks in advance!

1

There are 1 best solutions below

2
On BEST ANSWER

You need to use TreeView.ItemContainerStyle to achive this, here are couple of implementations which may help:

Strange Behaviour WPF TreeView ItemContainerStyle and ItemTemplate

WPF Double Click TreeviewItem Child Node