Home > OS >  What is the correct syntax for StringFormat in Binding tag?
What is the correct syntax for StringFormat in Binding tag?

Time:11-06

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