Hyperlinks in standard WPF windows

You can add Hyperlink elements in WPF documents and navigational containers. However, fi you have a standard WPF window, how do you do it?

Here is a possible solution: add a TextBlock with a Hyperlink inside it every time needed, and optionally customize the style of hyperlinks in your container’s Resources collection (e.g. to remove the underline and apply the foreground color of the TextBlock). It’s important, however, to also add an event setter for RequestNavigate to run custom code behind when the links get clicked:

<Window>
    <Window.Resources>
        <Style TargetType="Hyperlink">
            <Setter Property="Foreground" Value="{Binding Foreground, RelativeSource={RelativeSource AncestorType=TextBlock}}"/>
            <Setter Property="TextDecorations" Value="None"/>
            <EventSetter Event="RequestNavigate" Handler="Hyperlink_RequestNavigate"/>
        </Style>
    </Window.Resources>
    <TextBlock Foreground="Red">
        <Hyperlink NavigateUri="http://Google.com">
            Google
        </Hyperlink>
    </TextBlock>
</Window>
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
    e.Handled = true;
}
Advertisements

About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in WPF and tagged , , . Bookmark the permalink.

Add a reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s