nevada_scout nevada_scout - 1 year ago 129
C# Question

Change rectangle background on mouse hover

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?


Answer Source


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download