Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use stringformat in multibinding in WPF XAML

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

like image 360
ibrahimyilmaz Avatar asked Jun 13 '12 12:06

ibrahimyilmaz


People also ask

How do I format a string in XAML?

Notice that the formatting string is delimited by single-quote (apostrophe) characters to help the XAML parser avoid treating the curly braces as another XAML markup extension. Otherwise, that string without the single-quote character is the same string you'd use to display a floating-point value in a call to String.

How does MultiBinding work WPF?

WPF MultiBinding is very similar to the Binding , but allows to use multiple sources for the same target, so that the target changes whenever each one of the source value changes. These multiple sources are combined into one value via a multi value converter (which implements IMultiValueConverter interface).

What is a MultiBinding converter WPF?

Multibinding takes multiple values and combines them into another value. There are two ways to do multibinding, either using StringFormat or by a converter. The StringFormat is simple compared to a converter, so we will start with that first.


1 Answers

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)

like image 113
Thomas Levesque Avatar answered Oct 12 '22 03:10

Thomas Levesque