17

As you know StringFormat is of great importance for data representation in WPF. My problem is how to use StringFormat when multibinding in WPF?

If I give a very simple example:

We have variables,which are A and B and whose values are 10.255555 and 25.6999999

And we want to show them 10.2,25.6?

How can I do this with multibinding? Normally it is piece of cake with ValueConverter

Any help and ideas on this topic will be greately appreciated

ibrahimyilmaz
  • 18,331
  • 13
  • 61
  • 80

3 Answers3

60

Just set the StringFormat property on the MultiBinding; use placeholders ({0}, {1}...) for each binding in the multibinding, and include format specifiers if necessary (e.g. F1 for a decimal number with 1 decimal digit)

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0:F1}{1:F1}">
            <Binding Path="A" />
            <Binding Path="B" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

The {} part at the beginning is the format string is an escape sequence (otherwise the XAML parser would consider { to be the beginning of a markup extension)

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • Well, thx for your quick response but can you explain this briefly if it is possible in your answer? – ibrahimyilmaz Jun 13 '12 at 12:31
  • @ibrahimyilmaz, sorry, I thought the code was self explanatory... I added a short explanation. – Thomas Levesque Jun 13 '12 at 12:48
  • 1
    Hmmm. I've always been under the impression that `` required a converter. And indeed, when I attempt to set a multibinding as above, I get _"Cannot set MultiBinding because MultiValueConverter must be specified"_ at runtime. So...what's the secret sauce to get this answer to work? – Peter Duniho Jun 29 '19 at 23:59
  • Oh that's exactly I needed. The StringFormat in Bindings are totally ignored. I was so frustrated. – zORg Alex Sep 16 '19 at 07:16
9

If anyone is looking for "Time Formats" this is for 24hr Clock which is how I came to this post:

<TextBlock TextAlignment="Center">
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0:HH:mm} - {1:HH:mm}">
             <Binding Path="StartTime" />
             <Binding Path="EndTime" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

The leading 0: and 1: are the reference to the Bindings

[0:hh:mm tt] to display AM/PM

6

To simplify you could use two TextBlock/Labels to display the values.

If you are using .Net4, you can bind in a Run Inline element of a TextBlock

<TextBlock>
    <Run Text="{Binding A, StringFormat={}{0:F1}}"/>
    <Run Text="{Binding B, StringFormat={}{0:F1}}"/>
</TextBlock>
Shawn Kendrot
  • 12,425
  • 1
  • 25
  • 41
  • Between the 2 `Run`s will be a space. That's not like `StringFormat="{}{0:F1}{1:F1}"` mentioned above. Even writing `` will succeed only until you won't format XAML (like ReSharper does) and end up in `[CRLF][CRLF]` – Marcel Jan 12 '17 at 14:04