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:
  1. <TextBlock>  
  2.  <Hyperlink RequestNavigate="HandleLinkClick" NavigateUri="{Binding Path=Url}">  
  3.   <TextBlock Text="{Binding Path=LinkTitle}"/>  
  4.  </Hyperlink>  
  5. </TextBlock>  

And the C#:
  1. private void HandleLinkClick(object sender, RoutedEventArgs e) {  
  2.  Hyperlink hl = (Hyperlink)sender;  
  3.  string navigateUri = hl.NavigateUri.ToString();  
  4.  Process.Start(new ProcessStartInfo(navigateUri));  
  5.  e.Handled = true;  
  6. }  

No comments:

Post a Comment