I have some WPF textblocks in a stackpanel that I want to databind and format.
E.g. the following formats a date 24h style without the seconds part:
<TextBlock Text="{Binding MyCustomObject, StringFormat={}{0:HH:mm}}" />
Now, I would like to bind an integer and also display the + and - sign (i.e. +6 or -4).
<TextBlock Text="{Binding MyOtherCustomObject, StringFormat={}{0:+#}}" />
This however, does not work. Is this possible or do I have to write a complete converter just for this?
EDIT
Nikolays post led me to the answer:
<TextBlock Text="{Binding MyOtherCustomObject, StringFormat={}{0:+#;-#;''}}" />
In essence you provide a format for positive numbers, negative numbers and an optional part what to do with zero. In this case I stated that a zero should be displayed as an empty string.
Regards,
Michel
Overview of number formatting Numbers with two or more digits should be written as numerals unless they are at the start of a sentence (see examples). Numbers between 1000 and 9999 should contain no punctuation. Numbers with five or more digits should include commas (not decimal points or full stops).
Numeric format specifier (N) The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd. ddd…", where "-" indicates a negative number symbol if required, "d" indicates a digit (0-9), "," indicates a group separator, and "." indicates a decimal point symbol.
Try this:
<TextBlock Text="{Binding MyOtherCustomObject, StringFormat={}{0:+#;-#;''}}" />
This article has nice samples of int formatting - http://www.csharp-examples.net/string-format-int/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With