Tip: WPF 3.0 String.Format

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.'}"
    />

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>

...

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

Hooray for String.Format :) 

5 Responses to “Tip: WPF 3.0 String.Format”

  1. Doesn’t it bug you, though, that StringFormatConverter wasn’t included to begin with?

    I’m still wondering how two-way databinding works (if at all) with the StringFormat attribute.

  2. @Matt - there are lots of converters - some of them in WPF but marked internal - that I wish they’d included. But I think they made the right trade offs. The WPF team should be focussing on things that are really difficult to do (like binding infrastucture) and letting p&p, developers and third party libraries build the little helpful things on top (not wasting time building data grids :)).

  3. […] We Don’t Need No String.Format Binding! (Paul Stovell) […]

  4. Haha - I had a rather heated discussion with a colleague from our local user group on the drive home from Code Camp Oz, who suggested that my apps must not be “functional” because I build them without in-place editing in data grids!

  5. […] (This was inspired by a funny comment left by Matt Hamilton) […]

Leave a Reply