WPF - 鼠标悬停时更改标签外观
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22311403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF - Change label look on mouse over
提问by strider
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.
我有一个 WPF 标签,想在鼠标悬停或悬停时更改其外观。这个问题显示了如何使用 TextBlock 来做到这一点,而不是我想要使用触发器在 mouseover 上设置文本块前景的方法。这是不同的,因为使用Label,改变前景不起作用。
回答by Sheridan
Using the example from the question that you linked from, but changing the word TextBlockto Labelworks 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:
使用示例从问题,你从链接,但改变这个词TextBlock来Label的作品就好了改变Foreground,所以你必须提供更多的信息,如果你真的无法得到它的工作。尝试这个:
<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 Foregroundon the actual Labelelement, as you did in your answer, instead of in the Stylethen thatwould stop the Triggerfrom working, so don't do this:
请注意,如果您Foreground在实际Label元素上设置,就像您在答案中所做的那样,而不是在Stylethen中设置会停止Trigger工作,所以不要这样做:
<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>
回答by strider
Here is how you can do it. Ignore other properties, focus on Label.Style.
Using a Labelallows you to align text as I showed below. That does not work with TextBlock.
这是您如何做到的。忽略其他属性,专注于Label.Style. 使用 aLabel允许您对齐文本,如下所示。这不适用于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>

