I have a WPF label and want to change its look on mouse over or hover.
This question shows how to do it with TextBlock and not quite what I want using a trigger to set a textblock foreground on mouseover.
It's different because with Label
, changing foreground did not work.
Using the example from the question that you linked from, but changing the word TextBlock
to Label
works just fine for changing the Foreground
, so you'll have to provide more information if you really can't get it to work. Try this:
<Label Content="My colour changes just fine" HorizontalContentAlignment="Center"
VerticalContentAlignment="Center">
<Label.Style>
<Style TargetType="Label">
<Setter Property="Foreground" Value="Blue" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
Note that if you set the Foreground
on the actual Label
element, as you did in your answer, instead of in the Style
then that would stop the Trigger
from working, so don't do this:
<Label Content="My colour changes just fine" HorizontalContentAlignment="Center"
VerticalContentAlignment="Center" Foreground="Black">
<Label.Style>
<Style TargetType="Label">
<Setter Property="Foreground" Value="Blue" /> <!-- This won't work -->
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Red" /> <!--This won't work-->
</Trigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
Here is how you can do it. Ignore other properties, focus on Label.Style
.
Using a Label
allows you to align text as I showed below. That does not work with TextBlock
.
<Label Content="Hover over me" Name="lblSeasons" FontWeight="Bold" Foreground="DarkBlue" Width="150" HorizontalContentAlignment="Center" Height="50"
VerticalContentAlignment="Center" >
<Label.Style>
<Style TargetType="Label">
<Setter Property="Foreground" Value="Green"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Green"/>
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="BorderBrush" Value="Aqua"/>
</Trigger>
</Style.Triggers>
</Style>
</Label.Style>
</Label>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With