how to stop mouseover routed event to bubble up

778 Views Asked by At

I have to stop the mouse over event bubbling for following scenario.

  <Window.Resources>
    <x:Array x:Key="strings" Type="sys:String" 
        xmlns:sys="clr-namespace:System;assembly=mscorlib">
        <sys:String>One</sys:String>
        <sys:String>Two</sys:String>
    </x:Array>
    <DataTemplate x:Key="MyDataTemplate">
        <TextBlock Text="{Binding Path=IsMouseOver, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListViewItem}}"/>
    </DataTemplate>

    <DataTemplate x:Key="MyParentDataTemplate">
        <Expander HeaderTemplate="{StaticResource MyDataTemplate}">
            <ListView
              ItemsSource="{StaticResource strings}"
              ItemTemplate="{StaticResource MyDataTemplate}">
            </ListView>
        </Expander>
    </DataTemplate>

    <Style x:Key="ParentListViewItemStyle" TargetType="{x:Type ListViewItem}">
        <Setter Property="Foreground" Value="Blue"/>
    </Style>
</Window.Resources>
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="170"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <ListView ItemContainerStyle="{StaticResource ParentListViewItemStyle}"
              ItemsSource="{StaticResource strings}"
              ItemTemplate="{StaticResource MyParentDataTemplate}">
    </ListView>
</Grid>

The problem is when I do the mouse over on any child listviewitem. The mouse over of respective parent also get true. But I just dont want the parent to get mouseover.

I tried to attach the behavior and tried to set the e.Handled = true but this did not worked.

1

There are 1 best solutions below

0
On

IsMouseOver is not tied to whether the MouseOver event fired for an element. It is tied to whether the element is the Mouse.DirectlyOver or one of its ancestors. The ancestor(s) of the element under the mouse will always have their IsMouseOver set to true. I don't know what you are specifically trying to accomplish but if IsMouseOver doesn't suit your needs then you'll likely need to create and manage your own dependency property based on whatever your requirements are.