Search code examples
wpftriggersmouseclick-event

Handling a click event on the whole UserControl surface


I am using a TreeView in a MVVM scenario. As the display and context menu of children TreeViewItem depends on the type of view-model, I am using data-templates to select the right UserControl to display (much easier to manage than StyleSelector).

My problem is that I need to handle commands when the UserControl is clicked anywhere on its surface. I used EventTrigger directly attached to the UserControl but the click event is handled only when i click on the text of the TextBlock or the Image. Here a sample code:

<UserControl x:Class="FolderTreeView"
             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:i="http://schemas.microsoft.com/expression/2010/interactivity">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseLeftButtonDown">
            <i:InvokeCommandAction Command="{Binding Path=DisplayCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <StackPanel Orientation="Horizontal">
        <Image Source="{Binding Path=Icon}"/>
        <TextBlock Text="{Binding Path=DisplayName}"/>
    </StackPanel>  
</UserControl>

Any idea on I could get this to work?


Solution

  • Give your UserControl a background color. By default, the background color is Transparent, which means hit tests fall right through it

    <UserControl Background="White" ... />