Pigeonman
Pigeonman

Reputation: 57

How can I format this string in XAML?

I'm trying to convert a program that uses parts in Winforms, to WPF. I have run into a bit of trouble with this part. The program does this:

this.textBox.Properties.DisplayFormat.FormatString = "#,#;-#,#;-";

I'm not really sure what this is doing and I'm struggling to convert it to XAML for WPF. I know that I have to set it in here:

Text="{Binding x, Mode=OneWay, StringFormat={}{...}}"/>

but I'm not sure what would be the equivalent, since #,#;-#,#;- does not work. Thanks for any help! :)

Upvotes: 0

Views: 1397

Answers (1)

Tam Bui
Tam Bui

Reputation: 3048

According to the WinForms Format Specifiers, your original format string is saying:

  1. You want positive decimal numbers to look like whole numbers #,# (Example: 1234.5 will look like 1,234)
  2. You want negative decimal numbers to look like whole numbers -#,# (Example: -1234.5 will look like -1,234)
  3. You want zero to look like - (Example: -)

For WPF, you can use those same string format specifiers, but you need to pre-pend the formation with a {}. This is needed or else WPF will get confused with other markup extensions.

Here's an example:

Main.xaml

<StackPanel>
    <TextBlock Text="{Binding Value1, StringFormat={}{0:#,#;-#,#;-}}"/>
    <TextBlock Text="{Binding Value2, StringFormat={}{0:#,#;-#,#;-}}"/>
    <TextBlock Text="{Binding Value3, StringFormat={}{0:#,#;-#,#;-}}"/>
</StackPanel>

Main.xaml.cs

public double Value1 { get; set; }
public double Value2 { get; set; }
public double Value3 { get; set; }
public MainWindow()
{
    InitializeComponent();
    Value1 = 1234567.890f;
    Value2 = -987654.321f;
    Value3 = 0;
    this.DataContext = this;
}

Here's the final output:

enter image description here

Upvotes: 1

Related Questions