wpf 使用触发器在鼠标悬停时设置文本块前景
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4471771/
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
using a trigger to set a textblock foreground on mouseover
提问by Nadav Stern
I am trying to set block so its foreground color will change every time the mouse cursor goes over it, and this is my code:
我正在尝试设置块,以便每次鼠标光标移过它时它的前景色都会改变,这是我的代码:
<TextBlock Foreground="blue" Margin="18,234,5,-2" Grid.RowSpan="3">
<Underline>Remove Message</Underline>
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger Property ="IsMouseOver" Value="True">
<Setter Property= "Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
When I try to change the setter property to any other, for example FontSize="30"
, the event does occur.
例如,当我尝试将 setter 属性更改为任何其他属性时FontSize="30"
,该事件确实发生了。
回答by Andrei Pana
That is because the properties set on a control override the one defined in the Style, so your Foreground="blue" will override whatever you set in the style. To fix this, you can move the Foreground="blue" in the style and remove it from the properties of the control.
这是因为在控件上设置的属性会覆盖在样式中定义的属性,因此您的 Foreground="blue" 将覆盖您在样式中设置的任何内容。要解决此问题,您可以移动样式中的 Foreground="blue" 并将其从控件的属性中删除。
<TextBlock Margin="18,234,5,-2" Grid.RowSpan="3">
<Underline>Remove Message</Underline>
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property= "Foreground" Value="Blue"/>
<Style.Triggers>
<Trigger Property ="IsMouseOver" Value="True">
<Setter Property= "Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>