3

I have this WPF xaml binding element below:

<telerik:GridViewDataColumn DataMemberBinding="{Binding Value, StringFormat='0.00'}" />

If Value is 0, I would like it to display an empty string.

I've tried:

DataMemberBinding="{Binding TotalStops, StringFormat='{}{0:#.#0}'}"

But when Value is 0, it displays .00 instead of an empty string.

Orace
  • 7,822
  • 30
  • 45
Rod
  • 14,529
  • 31
  • 118
  • 230
  • There could be different ways to implement it, and WPF loves longcut ways (Converters, DataTriggers, etc.).. lol. But if I were you, I might have done something like this [answer](https://stackoverflow.com/a/4387810/395500). – Marshal Mar 24 '21 at 13:34

1 Answers1

4

In WPF, StringFormat support the ";" section separator.

Try this:

DataMemberBinding="{Binding Value, StringFormat={}{0:#.#0;(0);''}}"

This example shows 3 value formats: positive, negative, and zero value formatting from left to right, separated by semi-colons.

enter image description here

The image reference from article by Muhammad Shujaat Siddiqi


This is just not limited to WPF, this can work with where ever a string format is used in general.

double x = 0.00;
x.ToString("#.#0;;A BIG ZERO");
Console.WriteLine(x);
Orace
  • 7,822
  • 30
  • 45
Marshal
  • 6,551
  • 13
  • 55
  • 91
  • That works, thanks! I am getting a dark green squiggly line under the ```''``` back to back quotes (expecting a close brace), any ideas? Prolly safe to ignore – Rod Mar 24 '21 at 13:48
  • 1
    @Rod: You might have to escape the single quotes for zero-value formatting. I don't have a WPF project up, but I might try that out in a little bit. – Marshal Mar 24 '21 at 13:51
  • 1
    @Rod: Fixed it. Just remove the single quotes around the entire `StringFormat` expression. Please see the corrected answer abouve. – Marshal Mar 24 '21 at 13:57
  • 1
    Thanks for the extra insight, I'd give you a double check if I could, lol. – Rod Mar 24 '21 at 15:09
  • What if I have a TimeSpan that is ```0:00:00```, is it possible to replace that with blanks? I've tried ``` DataMemberBinding="{Binding LunchBreak, StringFormat={}{0:hh\\:mm\\:ss;;''}}"``` – Rod Mar 24 '21 at 19:00
  • 1
    @Rod: Unfortunately, the section formatter won't work on the TimeSpans (or may be DateTime too). One clean option is this case is a ValueConverter. – Marshal Mar 24 '21 at 20:26