处理整个UserControl表面上的单击事件

时间:2011-10-24 14:57:10

标签: wpf triggers mouseclick-event

我在MVVM场景中使用TreeView。由于子TreeViewItem的显示和上下文菜单取决于视图模型的类型,我使用数据模板来选择要显示的正确UserControl(比StyleSelector更容易管理)。

我的问题是,当在其表面的任何地方点击时,我需要处理命令。我使用EventTrigger直接附加到UserControl,但只有当我单击TextBlock或Image的文本时才会处理click事件。这是一个示例代码:

<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>

我有什么想法可以让它发挥作用吗?

1 个答案:

答案 0 :(得分:4)

为您的UserControl提供背景色。默认情况下,背景颜色为Transparent,这意味着命中测试正好通过它

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