Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - Change label look on mouse over

Tags:

label

wpf

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.

like image 252
strider Avatar asked Mar 10 '14 21:03

strider


2 Answers

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>
like image 159
Sheridan Avatar answered Oct 19 '22 18:10

Sheridan


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>
like image 1
strider Avatar answered Oct 19 '22 19:10

strider