How can I concatenate a string and a Binding value in a TextBlock

[Also read this post that makes the whole thing much easier] 

So I was running around in the WPF forums as usual and I started discussing how one can concatenate a string and a Binding to a textblock… so it would be something like this

<TextBlock Text=”Hello {Binding}”/>

You don’t have to be a WPF Expert to know that this would not work…. Yet it would be quite Handy to have… so I created a small Markup Extenstion that can do this for us…. I am going to post the full source because it is quite small !

public class ConcatStringExtension : MarkupExtension
{
//Converter to generate the string
class ConcatString : IValueConverter
{
public string InitString { get; set; }

#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//append the string
return InitString + value.ToString();
}

public
object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}

#endregion
}
//the value to bind to
public Binding BindTo { get; set; }
//the string to attach in front of the value
public string AttachString { get; set; }

public override object ProvideValue(IServiceProvider serviceProvider)
{
//modify the binding by setting the converter
BindTo.Converter = new ConcatString { InitString = AttachString };
return BindTo.ProvideValue(serviceProvider);
}
}

Thats’s it basically…. The Markup Extension will now modify the Binding that you specify by setting a converter that is able to attach a string infront of the value of the Binding…. So now we can do this….

<TextBlock Text=”{local:ConcatString AttachString=Hello, BindTo={Binding} }” />

Why did I decide to use a converter and set it to the binding, instead of just return the string passed (AttachString ) and the value of the binding concatenated? well very simple because of the binding…. what would happen then when the binding value changed!!! A markup extension will only spit an object for the parser yet if we modify the binding we would achieve what we what i.e that the binding still updates….

Hope you like this…. Regards