Wednesday, December 24, 2008

WPF Hyperlink Open Browser

As my first post, I want to do something simple. Here was my problem: I wanted to have a hyperlink in WPF that would open in the browser when my link was clicked. In addition, I wanted the URL and title (display text) of the link to be obtained from a databinding. The following example assumes that the hyperlink has a parent that has a databinding where we can get the Url and LinkTitle fields from.

It can be achieved like this:
XAML:

<TextBlock>
<Hyperlink RequestNavigate="HandleLinkClick" NavigateUri="{Binding Path=Url}">
<TextBlock Text="{Binding Path=LinkTitle}"/>
</Hyperlink>
</TextBlock>

And the C#:

private void HandleLinkClick(object sender, RoutedEventArgs e) {
Hyperlink hl = (Hyperlink)sender;
string navigateUri = hl.NavigateUri.ToString();
Process.Start(new ProcessStartInfo(navigateUri));
e.Handled = true;
}

No comments:

Post a Comment