Search code examples
wpfpropertiesstylescontrolsrectangles

Change style of a child control on MouseOver in WPF


I have a custom control that holds two Rectangles and several TextBoxes. I wish to change the background color of the Rectangle on MouseOver.

I add trigger as following:

  <Rectangle 
            Grid.Column="1" 
            Fill="#FF383838" 
            Grid.ColumnSpan="3" 
            Margin="0,4,4,4">

            <Rectangle.Style>
                <Style TargetType="{x:Type Rectangle}">
                    <Setter Property="Fill" Value="#FF383838" />
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Fill" Value="#FF575757" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Rectangle.Style>

        </Rectangle>

But since rectangle is part of my control, I assume the event is not firing.


Solution

  • Setting a property via XAML will be applied over the style properties that you try to set. To fix this, remove Fill=#FF383838 so you should have:

    <Rectangle Grid.Column="1"
               Grid.ColumnSpan="3"
               Margin="0,4,4,4">
    //... rest of code here