在不丢失悬停颜色的情况下更改超链接前景 [英] Changing Hyperlink foreground without losing hover color

查看:31
本文介绍了在不丢失悬停颜色的情况下更改超链接前景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 WPF 应用程序,我希望我的一些超链接默认为蓝色,而其他超链接为绿色.没问题——我可以设置 Foreground:

I'm writing a WPF app, and I want some of my hyperlinks to be the default blue, and others to be green. No problem -- I can just set Foreground:

<TextBlock><Hyperlink Foreground="#0C0">Mark as done</Hyperlink></TextBlock>

问题是,当我这样做时,悬停效果消失了.在普通的超链接中,当我将鼠标移到链接上时,它会变成红色,而当我将鼠标移开时,它会变回蓝色.但是在分配了 Foreground 属性的超链接中,它始终是那种颜色——悬停时的红色完全被抑制.

The trouble is, when I do this, the hover effect goes away. In a normal Hyperlink, when I move the mouse over the link, it turns red, and when I move the mouse away, it goes back to blue. But in a Hyperlink with the Foreground property assigned, it's always that color -- the red-on-hover is totally suppressed.

如何在不丢失默认悬停行为和颜色的情况下更改超链接的颜色?

How can I change a Hyperlink's color, without losing the default hover behavior and color?

推荐答案

直接设置前景(正如您所做的那样)不起作用,并且在样式中设置它也不起作用,除非 您从默认的超链接样式(必须包括 OnMouseOver 触发器)派生"该样式.所以这是有效的:

Setting the Foreground directly (as you've done) doesn't work, and setting it in a Style doesn't work either, unless you "derive" that style from the default Hyperlink style (which must include the OnMouseOver trigger). So this works:

<TextBlock>
    <Hyperlink>
        <Hyperlink.Style>
            <Style TargetType="Hyperlink"
                   BasedOn="{StaticResource {x:Type Hyperlink}}">
                <Setter Property="Foreground" Value="#0C0"/>
            </Style>
        </Hyperlink.Style>
        Mark as done
    </Hyperlink>
</TextBlock>

将该样式提取回 Window 资源并使用键引用它可能会使 XAML 更具可读性,但上面的代码可以完成这项工作.

Extracting that style back into the Window resources and referencing it with a key would probably make for more-readable XAML, but the above code does the job.

这篇关于在不丢失悬停颜色的情况下更改超链接前景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆