NPVN
NPVN

Reputation: 95

Setting properties on child elements in trigger on parent element

I have a user cotrol which consists of a canvas that contains an ellipse and a viewbox. The ellipse is the background, and the viewbox is filled at runtime with graphics loaded from another assembly. I'm having problems creating a "hot" behavior for my control, so that the ellipse changes color when the mouse is over it.

If I put a trigger on the ellipse then the color changes, but it changes back when the mouse moves over the graphics in the viewbox because the viewbox is not a child of the ellipse.

From what I've read, it should be possible to set properties on child elments from a trigger on the parent element. However, I can't get this to work. My code looks like this:

    <Viewbox Margin="5" >
        <Viewbox.Resources>
            <SolidColorBrush x:Key="HotColor"  Color="Blue"/>
            <SolidColorBrush x:Key="ColdColor"  Color="Red"/>
            <Style TargetType="Canvas" x:Key="BackgroundStyle">
                <Setter Property="Ellipse.Fill" Value="{StaticResource ColdColor}"/>
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter Property="Ellipse.Fill" Value="{StaticResource HotColor}"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Viewbox.Resources>
        <Canvas Width="44.000" Height="44.000" Style="{StaticResource BackgroundStyle}">
            <Ellipse Width="44" Height="44"/>
            <Viewbox Name="ButtonGraphics"/>
        </Canvas>
    </Viewbox>

The result is that I get no color on my ellipse at all. Funny enough, if I try setting Ellipse.Opacity in stead, it works but affects both the ellipse and the graphics! So it looks like it is being applied to the canvas, and not the ellipse?

Upvotes: 0

Views: 3816

Answers (2)

Abe Heidebrecht
Abe Heidebrecht

Reputation: 30498

When you use a Setter with a ClassName.PropertyName property, you aren't setting PropertyName on all ClassName objects. Instead, you are setting ClassName.PropertyName on the styled object type (in your case Canvas). Giving a ClassName.PropertyName is just a class qualified path to that property. For Opacity, Canvas.Opacity == Ellipse.Opacity == UIElement.Opacity.

Now, in order to accomplish what you want, setting IsHitTestVisible=False on the ButtonGraphics ViewBox will prevent the graphics from intercepting mouse events.

Upvotes: 1

Rachel
Rachel

Reputation: 132558

What about just setting IsHitTestVisible=False on your ViewBox? This would remove it from hit-testing altogether and mouse events would register to your Ellipse.

Upvotes: 1

Related Questions