wpf mouseover margin in stackpanel

1.7k views Asked by At

I have a tab item, header having the following form: image_margin_textblock.

The trigger IsMouseOver is working properly when the mouse cursor is over the image, and also over the textblock. But, when the mouse cursor is over the margin between the Image and Textblock, the IsMouseOver trigger is not fired. This creates an annoying flickering effect.

Do you have any ideas how to achieve mouseover trigger over the margin?

Here is the code:

<TabItem.Header>
<ContentControl>
    <ContentControl.Template>
        <ControlTemplate>
            <StackPanel x:Name="sp0" Orientation="Horizontal">
                <StackPanel x:Name="sp1" Orientation="Horizontal" Background="Blue">
                    <Image VerticalAlignment="Center" HorizontalAlignment="Center" Source="tab1.png"/>
                </StackPanel>
                <TextBlock Margin="10,0,0,0" Text="Tab1" VerticalAlignment="Center"/>
            </StackPanel>
            <ControlTemplate.Triggers>
                <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}" Value="True">
                    <Setter TargetName="sp1" Property="StackPanel.Background" Value="Green"/>
                </DataTrigger>
                <Trigger SourceName="sp0" Property="IsMouseOver" Value="True">
                    <Setter TargetName="sp1" Property="StackPanel.Background" Value="Green"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </ContentControl.Template>
</ContentControl>

Thank you.

2

There are 2 answers

0
Rohit Vats On BEST ANSWER

Set Background on outer StackPanel to Transparent so that margin also participates in HitTest (i.e. respond to mouse events).

Right now only image and TextBlock area responds to MouseOver event. Setting background to Transparent will work.

<StackPanel x:Name="sp0" Orientation="Horizontal" Background="Transparent">
0
Mat J On

Set background of your StackPanel to Transparent. This makes it visible to hit test.

    <StackPanel x:Name="sp0" Orientation="Horizontal" Background="Transparent">
            <StackPanel x:Name="sp1" Orientation="Horizontal" Background="Blue">
                <Image VerticalAlignment="Center" HorizontalAlignment="Center" Source="tab1.png"/>
            </StackPanel>
            <TextBlock Margin="10,0,0,0" Text="Tab1" VerticalAlignment="Center"/>
    </StackPanel>