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.
- 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.
- 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.