Saturday, 12 October 2013

WPF - How to use Hyperlink

Requirement:
Add a Hyperlink to WPF window/page; clicking on which should open up a web browser with the url assigned to the hyperlink.

Solution:
Add a Hyperlink control to your page. It need to be in a container like a TextBlock because the control cannot exist independantly. Handle the RequestNavigate event and do our custom actions required, in our case spawn a new process to open up a web browser to navigate to the specified url.
XAML
<TextBlock>          
    <Hyperlink NavigateUri="http://www.google.com" RequestNavigate="Hyperlink_RequestNavigate">
        Click here
    </Hyperlink>
</TextBlock>
Codebehind
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
    e.Handled = true;
}

No comments:

Post a comment