Home > Software design >  WPF Binding with StringFormat-ting for float values
WPF Binding with StringFormat-ting for float values

Time:10-06

I know there are a lot of answers to this, but in my case it doesn't work, looks like it's something specific I'm struggling with.

I have this piece of code on my XAML side, but for some reason these text blocks show the raw float values rounded up to 2 decimal points, whereas, based on the string formatting it supposed to show up to 4 decimal points if there are. In my case I was expecting to show my Y value to show in tooltip 12.1864, but it shows 12.19. How can I make it format the way I want?

<TextBlock>
    <Run Text="X: "/>
    <Run Text="{Binding XValue, StringFormat={}{0:#.####}, Mode=OneWay}"/>
</TextBlock>
<TextBlock>
    <Run Text="Y: "/>
    <Run Text="{Binding YValue, StringFormat={}{0:#.####}, Mode=OneWay}"/>
</TextBlock>

enter image description here

CodePudding user response:

Your code works fine for me

<Window
    x:Class="BindingFormatTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:BindingFormatTest"
    SizeToContent="WidthAndHeight">

    <Window.DataContext>
        <local:MainViewModel />
    </Window.DataContext>

    <StackPanel>
        <TextBlock>
            <Run Text="X: " />
            <Run Text="{Binding XValue, StringFormat={}{0:#.####}, Mode=OneWay}" />
        </TextBlock>
        <TextBlock>
            <Run Text="Y: " />
            <Run Text="{Binding YValue, StringFormat={}{0:#.####}, Mode=OneWay}" />
        </TextBlock>
    </StackPanel>
</Window>

public class MainViewModel
{
    public double XValue { get; } = 12.345678;

    public double YValue { get; } = 23.456789;
}

enter image description here

Try using a tool such as WPFSnoop to check that the data context and the values are really what you expected.

CodePudding user response:

I have checked your code & it works fine as expected with 4 decimal points, enter image description here

Please find code below

    public string XValue { get; set; }

    public string YValue { get; set; }

    private void setXYValue()
    {
        XValue = "19.45678";
        YValue = "20.12345";

        OnPropertyChanged(nameof(XValue));
        OnPropertyChanged(nameof(YValue));
    }



      <StackPanel Orientation="Vertical">
        <TextBlock>
            <Run Text="X: "/>
            <Run Text="{Binding XValue, StringFormat={}{0:#.####}, Mode=OneWay}"/>  
        </TextBlock>
            <TextBlock>
            <Run Text="Y: "/>
            <Run Text="{Binding YValue, StringFormat={}{0:#.####}, Mode=OneWay}"/>
            </TextBlock>
        </StackPanel>
  • Related