Welcome to MSDN Blogs Sign in | Join | Help

Pedro Silva's Blog

Development lead on Visual Studio Platform team focusing on the extensibility of Visual Studio.

Syndication

News

My name is Pedro Silva. I’m the development lead in the Visual Studio Platform team at Microsoft, working on VS Extensibility features, enabling VS extensions and the VS SDK.

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

WPF LinkLabel

WPF doesn't have a built in LinkLabel control as you'd find in WinForms. But, I have found a couple of neat ways of doing one in WPF. The first was creating a new WPF control that derives from Label and then adds functionality to have it behave like a hyperlink. While this will certainly work, it's more work than I was hoping that it would require.

Luckily, I ran across this post by Alessandro that composed a LinkLabel from a WPF Label control and a HyperLink object. This was done completely in XAML so no custom code was needed to create this behavior. And, the best part is that done this way, I was able to use databinding to set the text of the hyperlink and the the URI that would get launched when the user clicks it. Very cool... :)

The XAML snippet below shows how to define the LinkLabel composite and use databinding on its pieces (this binds to some simple XML that provides the link text and URI):

<Label x:Name="label" x:Uid="label">

      <Hyperlink x:Name="hyperlink" x:Uid="hyperlink" NavigateUri="{Binding XPath=Link/@Uri}"

                 Hyperlink.RequestNavigate="hyperlink_RequestNavigate">

           <TextBlock Text="{Binding XPath=Link}" />

      </Hyperlink>

</Label> 

The only code I had to write was to handle the navigation event for the HyperLink, and then launch your favorite internet browser in response.

private void hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)

{

    string uri = e.Uri.AbsoluteUri;

    Process.Start(new ProcessStartInfo(uri));

 

    e.Handled = true;

}

One interesting thing I noticed is that you can either handle the Click or RequestNavigate event. If you handle RequestNavigate, the event only gets fired if you have a valid URI defined. Otherwise, the event isn't even fired. On the other hand, the Click event is always fired, so you need to put in error handling for invalid URIs. So, I'm going to tend to use RequestNavigate because it simplifies coding the event handler.

 

Published Friday, April 17, 2009 3:30 PM by PedroSilva

Filed under: , ,

Comments

# Anith &raquo; WPF LinkLabel @ Friday, April 17, 2009 6:44 PM

PingBack from http://www.anith.com/?p=29785

Anith &raquo; WPF LinkLabel

# WpfAboutBox: Dialog Layout and Styles @ Friday, May 08, 2009 1:51 PM

I wanted to make an AboutBox that is as easy to use as the one that comes with Winforms. But, I also

Pedro Silva's Blog

New Comments to this post are disabled
Page view tracker