Reputation: 983
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.
Upvotes: 5
Views: 16160
Reputation: 266
The way to change background color to gradient for rectangle:
<Rectangle Width="128" Height="128" StrokeThickness="1" Stroke="Black">
<Rectangle.Style>
<Style TargetType="Rectangle">
<Setter Property="Fill" Value="Red"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Fill">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
<GradientStop Color="#FF2824A0"/>
<GradientStop Color="#FF78B9DD" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Rectangle.Style>
</Rectangle>
Upvotes: 0
Reputation: 185280
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)
Upvotes: 11
Reputation: 6651
You could add two Triggers
for IsMouseOver
property: when it is true
(ie mouse is over the rectangle), here I change the background to Blue, otherwise Red!
<Rectangle.Resources>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Blue"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="False">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Rectangle.Resources>
Upvotes: 0
Reputation: 35594
the simplest way must be something like this (beware, no good style):
<Image>
<Image.Style>
<Style TargetType="Image">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Source" Value="myimage.png"/>
</Trigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
Upvotes: 0
Reputation: 17966
This answer is close to yours I believe. They are setting the background to a brush instead of an image. - Changing dynamically created button's background in WPF
Upvotes: 0