Home > Software design >  How to escape "{0:F2}" in StringFormat="{0:F2}" as a string instead of binding e
How to escape "{0:F2}" in StringFormat="{0:F2}" as a string instead of binding e

Time:11-07

What is the correct syntax for StringFormat in the second label?

<Label Text="{Binding StringFormat='{0:F2}', Source={x:Static sys:Math.PI}}"/>
<Label>
    <Label.Text>
        <Binding StringFormat="{0:F2}" Source="{x:Static sys:Math.PI}"/>
    </Label.Text>
</Label>

enter image description here

CodePudding user response:

Is this a WPF application?
In WPF, Label does not have a Text property. There is a Content property, which is of type object. And therefore for this property no conversion to a string is used and, accordingly, the String Format is not applied.

For a TextBlock:

<TextBlock Text="{Binding StringFormat='{0:F2}', Source={x:Static sys:Math.PI}}"/> 

<TextBlock Text="{Binding StringFormat={}{0:F2}, Source={x:Static sys:Math.PI}}"/>

<TextBlock>
    <TextBlock.Text>
        <Binding StringFormat="{}{0:F2}" Source="{x:Static sys:Math.PI}"/>
    </TextBlock.Text>
</TextBlock>

<TextBlock>
    <TextBlock.Text>
        <Binding Source="{x:Static sys:Math.PI}">
            <Binding.StringFormat>
                <sys:String>{0:F2}</sys:String>
            </Binding.StringFormat>
        </Binding>
    </TextBlock.Text>
</TextBlock>

<Binding>
    <Binding.StringFormat>
        <sys:String>{0:F2}</sys:String>
    </Binding.StringFormat>
    <Binding.Source>
        <x:Static Member="sys:Math.PI"/>
    </Binding.Source>
</Binding>

  • Related