Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

HyperlinkButton Gotcha

0.00/5 (No votes)
14 Apr 2010 1  
HyperlinkButton Gotcha

The new Silverlight 2 HyperlinkButton control is one of the few controls that there is no exact match for between Silverlight 2 and WPF, and its use is quite simple. You specify a value for the NavigateUri property, which defines where the link will navigate to (it's all in the name!) and also specify a value for the TargetName property, which defines the target window or frame to navigate such as _blank, or _self.

The following code examples show how to define a HyperlinkButton that shows "Titan Blog" and will navigate to this blog in a new window:

<HyperlinkButton Content="Titan Blog"

                 NavigateUri="http://cloudstore.spaces.live.com"

                 TargetName="_blank" />

The type of the NavigateUri property is actually a Uri. Like a lot of properties in WPF and Silverlight 2, you can specify a string instead of an instance of the actual type and a converter is used to convert the source string into the required type (such as Background="Red" being converted into a SolidColorBrush). This is what happens to the sting specified in the NavigateUri property in the previous code example. The following code example shows how to define the previous HyperlinkButton in code:

HyperlinkButton targetLink = new HyperlinkButton();
targetLink.Content = "Titan Blog";
targetLink.NavigateUri = new Uri("http://cloudstore.spaces.live.com");
targetLink.TargetName = "_blank";

Get to the point, Derek! Well the point is this: when it comes to data-binding to a HyperlinkButton control, you might be tempted to bind a string to the NavigateUri property. Don't! Whilst this doesn't bring about a catastrophic end to your application, it also won't result in your HyperlinkButton actually working. There are two potential solutions to this problem.

  1. Bind a Uri value to the NavigateUri property. This is fine if you have control over the underlying data model that you are binding to and provides the simplest solution.
  2. Create a custom converter that can convert a string to a Uri. Whilst this is a particularly simple converter to write, it will muddy up your nice neat XAML by requiring you to specify the converter in the binding.

I used solution 1 this time around because I had access to my data model and could change it easily, but in the future, I could just as easily be tempted to use option 2.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here