Reputation: 41812
Is there an easy way to transform or format a string as part of WPF data binding?
Suppose I want to create a WPF Hyperlink element based on a string tag.
<Hyperlink NavigateUri="{Binding Tag}">
<Run Text="{Binding Tag}" />
</Hyperlink>
But I need to transform the Tag first for the NavigateUri property to make it a true hyperlink or PackUri.
For instance, if my tag were "folksonomy" I'd want to create a string like: http://www.example.com/tags/tagview?tag=folksonomy
What's the best way to achieve this? Is there a string manipulation function in XAML? Do I have to write a converter? Do I have to build a whole separate ViewModel class just to do a little string formatting?
UPDATE: There appears to be something strange going on with the Hyperlink element. I can get the StringFormat syntax suggested in the answers to work for the Text property of an ordinary TextBlock, but not for the NavigateUri property of a Hyperlink.
As one answer noted, this is likely due to the fact that the NavigateUri property officially takes a Uri, not a string. Apparently a custom converter or ViewModel property will be required.
Upvotes: 1
Views: 4090
Reputation: 178770
You can use the string formatting capabilities of bindings:
<Hyperlink NavigateUri="{Binding Tag, StringFormat=http://www.example.com/tags/tagview?tag={0}}">
<Run Text="{Binding Tag}" />
</Hyperlink>
Upvotes: 3
Reputation: 1114
For anyone else stumbling across this thread seeking a solution, I found Foovanadil's suggested IValueConverter worked well for me.
<TextBlock>
<Hyperlink Name="lnkGoogle" NavigateUri="{Binding Path=Alert.Query,Converter={View:UriConverter},ConverterParameter=google}" RequestNavigate="Hyperlink_RequestNavigate">
Find news on Google
</Hyperlink>
</TextBlock>
With the converter class in my codebehind:
public class UriConverter : MarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string address = string.Empty;
switch ((string)parameter)
{
case "google":
address = "http://www.google.co.uk/news?q=" + value;
break;
}
Uri path = new Uri(@address);
return path;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new System.NotImplementedException();
}
public override object ProvideValue(System.IServiceProvider serviceProvider)
{
return this;
}
}
Upvotes: 2
Reputation: 6501
Like Kent said you can use string formatting assuming you are on .NET 3.5 SP1 (string formatting was added as part of SP1). Good Samples here: http://blogs.msdn.com/b/llobo/archive/2008/05/19/wpf-3-5-sp1-feature-stringformat.aspx
If you aren't on .NET 3.5 SP1 or the string format approach becomes too messy you would want to us an IValueConverter http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx
Upvotes: 3