Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Hyperlink foreground without losing hover color

Tags:

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>

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?

like image 462
Joe White Avatar asked Aug 10 '09 02:08

Joe White


2 Answers

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>

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.

like image 180
Matt Hamilton Avatar answered Oct 03 '22 04:10

Matt Hamilton


You should build your Hyperlink like this

<TextBlock Width="Auto" HorizontalAlignment="Center">
    <Hyperlink Click="ForgotPassword_Clicked">
        <TextBlock Text="Forgot Password?"/>
    </Hyperlink>
</TextBlock>

And then this style should work for you

<Style TargetType="{x:Type Hyperlink}">
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="Foreground" Value="Blue" />
        <Setter Property="TextBlock.TextDecorations" Value="{x:Null}" />
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Foreground" Value="Red" />
                <Setter Property="TextBlock.TextDecorations" Value="Underline" />
            </Trigger>
        </Style.Triggers>
    </Style>
like image 42
Riz Avatar answered Oct 03 '22 03:10

Riz