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

21 thoughts on “How can I concatenate a string and a Binding value in a TextBlock

  1. Sorry, forgot, this could be great in creating wpf configuration file. which is, i can create a config file, but markups are wpf generated, then we can use workflow to modify it dynamically. What do you think ?

  2. aaa… yes I suggested that in the forum post yet the Marhup Extention is a nice way of doing it as well…. maybe a bit over complicated but you know it is always a nice solution🙂

  3. thanks a lot sacha… I must admit, your blog is on my feed reader….🙂 Explorer3D is really cool !!!!!! and the post that you posted on Viewport2DVisual3D helped me a lot🙂 in fact all your post are really great!!!!🙂

  4. To go into more detail, something like this:

    And the value converter would look something like this:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
    string strBoundString = System.Convert.ToString(value);

    string strStringToParse = parameter as String;

    string strNewString = strStringToParse.Replace(“%s”, strBoundString);

    return strNewString;
    }

  5. Ack, the above parser didn’t like my textblock example, lets try again:

    <TextBlock Text=”{Binding Path=EventViewerInstanceCount, Converter={StaticResource ConcatStringConverter}, ConverterParameter=’NewString (%s)’}” />

  6. What if I have two or more words in my AttachString?

    Example:
    Text=”{local:ConcatString AttachString=User details:, BindTo={Binding Path=UserName}}”

  7. You can just use stringformat like you would in code behind. This shows an example using multi binding to display an ID and a Name property like this:
    [72] – My Item Name

    You need empty braces {} to start or a space to start the format otherwise it won’t compile.

  8. Some reason it didn’t like my xaml either. Lets try again without angle brackets

    TextBlock
    TextBlock.Text
    MultiBinding StringFormat=”{}[{0}] – {1}”
    Binding Path=”ID”/
    Binding Path=”Name”/
    /MultiBinding
    /TextBlock.Text

    • {Binding Path=YourBindingPath, StringFormat='{0} Hello’}

      Reversed is not possible, I tried it using these test cases.

      ‘Hello {0}’ = working
      ‘ {0} Hello’ = working
      ‘{0} Hello’ = error

      I want to display size of file like
      ‘{0} MB’ or 4 MB for example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s