How do I use EventToCommand to handle routed event from a child control of a WPF panel?

1k Views Asked by At

I have a control that inherits from Panel. This control creates button controls based on a collection bound to the custom control. How to I handle the button.click event from the children? Here is my XAML. The command does not get executed.

   <ScrollViewer HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto" Height="Auto" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
      <control:TreeContainer HorizontalAlignment="Center" 
                             Width="Auto" Height="Auto" Margin="8,8,8,8" VerticalBuffer="20" 
                             RootNode="{Binding Path=RootNode}" 
                             ChildrenNodes="{Binding Path=ChildrenNodes}">
         <i:Interaction.Triggers>
            <i:EventTrigger EventName="Button.Click">
               <cmd:EventToCommand Command="{Binding Path=TreeContainerClickCommand, Mode=OneWay}" PassEventArgsToCommand="True" />
            </i:EventTrigger>
         </i:Interaction.Triggers>
      </control:TreeContainer>
   </ScrollViewer>
1

There are 1 best solutions below

2
On

you can set a Style to all Buttons in the control, and bind the command there. When you add the Style with TargetType="Button" to the TreeContainer, it will be applied to all Buttons in the TreeContainer.

<ScrollViewer HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto" Height="Auto" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<control:TreeContainer HorizontalAlignment="Center" 
                         Width="Auto" Height="Auto" Margin="8,8,8,8" VerticalBuffer="20" 
                         RootNode="{Binding Path=RootNode}" 
                         ChildrenNodes="{Binding Path=ChildrenNodes}">
  <control:TreeContainer.Resources>
    <Style TargetType="Button">
      <Setter Property="Command" Value="{Binding Path=TreeContainerClickCommand, Mode=OneWay}"/>
    </Style>
  </control:TreeContainer.Resources>
 </control:TreeContainer>

if do not have access to the TreeContainer ViewModel in your Buttons, you'll have to access it via RelativeSource:

<Setter Property="Command" 
        Value="{Binding Mode=OneWay,
                        Path=DataContext.TreeContainerClickCommand,
                        RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type control:TreeContainer}}}" />

note that you'll have to change the Path to DataContext.* because your Source is TreeContainer, not its ViewModel.

edit: if you really need an EventTrigger to get your EventArgs, you could do the same like above with the Template of the Button. Then you can define a new Template in which you can use your interaction-Triggers.