Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my StringFormat not work in WPF [duplicate]

I've seen a few questions like this on SO but none of the answers work for me! Here's my abridged code:

<Grid Margin="10,4,2,3">

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="150" />
    </Grid.ColumnDefinitions>

    <Image Name="myImage" />

    <WrapPanel Orientation="Vertical" Grid.Column="1" >
        <Label x:Name="labelDimensions" Content="Image Dimensions" />
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="3*" />
                <ColumnDefinition Width="1*" />
                <ColumnDefinition Width="3*" />
            </Grid.ColumnDefinitions>

            <Label Grid.Column="0" 
                   x:Name="imageWidth" 
                   Content="{Binding Path=ActualWidth, 
                             ElementName=myImage, 
                             StringFormat={}{0:1234.5}}" />
            <Label Grid.Column="1" x:Name="label3" Content=" x " />
            <Label Grid.Column="2" 
                   x:Name="imageHeight" 
                   Content="{Binding Path=ActualHeight, 
                             ElementName=myImage, 
                             StringFormat={}{0:1234.5}}" />
        </Grid>
    </WrapPanel>

</Grid>

I am expecting to see, below the 'Image Dimensions' label, something like "641.3 x 480.0" but no matter what I do, it comes out with stuff like "641.30000000 x 480".

I've formats like {0:1234.5} and {0:#,#.#} but nether have any effect. I've also tried ConentStringFormat as one SO answer suggested but that didn't even compile.

Any advice would be hugely appreciated.

like image 965
user41013 Avatar asked Jan 19 '17 22:01

user41013


2 Answers

Use the ContentStringFormat instead.

StringFormat is only used when binding to a property of type String. The Content property of Label is of type object as you can see here, so StringFormat will not work.

like image 94
CodingYoshi Avatar answered Oct 01 '22 13:10

CodingYoshi


Try giving StringFormat={}{0:F1} :

<Label Grid.Column="0" 
       x:Name="imageWidth" 
       Content="{Binding Path=ActualWidth, 
                 ElementName=myImage, 
                 StringFormat={}{0:F1}" />
<Label Grid.Column="1" x:Name="label3" Content=" x " />
<Label Grid.Column="2" 
        x:Name="imageHeight" 
        Content="{Binding Path=ActualHeight, 
                  ElementName=myImage, 
                  StringFormat={}{0:F1}" />
like image 21
phabtar Avatar answered Oct 01 '22 13:10

phabtar