String.Format MultiBinding for WPF

You are looking at revision 3 of this page, which may be out of date. View the latest version.

One of the upcoming additions in .NET 3.5 SP1 is a StringFormat parameter you can pass along with your bindings. Sacha Barber has an example of how to use it:

<TextBlock 
    Text="{Binding Path=AccountBalance, StringFormat='You have {0:c} in your bank account.'}" 
    /></pre>

However, if you can't install the service pack or you haven't been able to upgrade to .NET 3.5, don't fret. Here's a snippet, albeit with a few more lines of code, to perform the same thing:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding
            ConverterParameter="Hello {0} {1}, you have {2:c} in your account"
            Converter="{StaticResource StringFormatConverter}"
            >
            <Binding Path="FirstName" />
            <Binding Path="LastName" />
            <Binding Path="AccountBalance" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

The converter would be implemented as so:

class StringFormatConverter : IMultiValueConverter
{
   public object Convert(object[] values, ..., object parameter) 
   {
       return string.Format(parameter.ToString(), values);
   }
}

You can find this and more binding tricks in my WPF Platform Examples solution.

Last revised: 13 Dec, 2009 07:32 AM History
You are looking at revision 3 of this page, which may be out of date. View the latest version.

Discussion

Your Comments

Used for your gravatar. Will not be public.

Posting code? Indent it by four spaces to make it look nice. Learn more about Markdown.

Preview