Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change rectangle background on mouse hover

Tags:

c#

wpf

So I have a rectangle with no background and I want to give it a background gradient when the user hovers their mouse over it, and then remove the gradient when the mouse leaves the rectangle.

Please can someone post the code that is needed for this, and tell me where to put it in the .cs/xaml file?

Thanks.

like image 777
nevada_scout Avatar asked Jun 01 '11 13:06

nevada_scout


1 Answers

This:

<Rectangle Width="100" Height="100" StrokeThickness="1" Stroke="Black">
    <Rectangle.Style>
        <Style TargetType="{x:Type Rectangle}">
            <Setter Property="Fill" Value="Transparent" />
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Fill">
                        <Setter.Value>
                            <!-- Change ImageSource to what image you want to use -->
                            <ImageBrush ImageSource="C:/Users/Public/1.png" />
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Rectangle.Style>
</Rectangle>

(Note that if you set Fill="Transparent" on the Rectangle itself the Trigger will not work because of dependency property value precedence)

like image 100
H.B. Avatar answered Nov 07 '22 09:11

H.B.