Have you ever wanted to construct a dynamic query string for your Hyperlinks in WPF or Silverlight? Perhaps it’s the web developer in me, but I find myself wanting to do this all the time.
Sadly, the Hyperlink element’s NavigateUri property makes this extremely difficult. Since the NavigateUri property’s target type is a Uri, not a string, you can’t use the convenient StringFormat syntax to create dynamic URLs. I started a StackOverflow question to discuss how to use StringFormat with the NavigateUri property. The best approach for now appears to be to write an IValueConverter that will create the Uri from a string.
This works if you only need to apply a single value. But what if you need to supply multiple values to generate a querystring with several parameters?
A post from Paul Stovell pointed me in the right direction: prior to the introduction of special StringFormat syntax in .NET 3.5 SP1, you needed to use multibinding to manipulate strings. We can use this older method to generate the Uri we need for the Hyperlink.
First, create a converter that implements IMultiValueConverter.
Remember to add the converter application resources in your App.xaml file, so you can reference it throughout your application.
Then you can use it wherever you need to dynamically create a URI within your WPF or Silverlight application.
Whew. That’s a lot of extra work just to generate a URL for a hyperlink!
Notice that I had to escape the ampersand in the format string supplied in the ConverterParameter. Since XAML is based on XML, not HTML, you must escape the ampersand within attribute values. This catches me every time.
Generating dynamic URLs is such a basic operation for building navigation-style WPF or Silverlight applications, I’m surprised the folks at Microsoft didn’t create a helper syntax to handle this cleanly.
Leave a Comment