Wednesday, January 14, 2015

Blank when Zero

I have a common requirement to replace zero values in a data grid text column with spaces. This can be done easily with a converter or a trigger, but I found a way to do it with a StringFormat using a little known feature called conditional formatting. This allows you to define up to three different formats depending on whether the number is positive, negative, or zero.

In the example XAML below, I want the Orphaned ID to be blank if the bound value is zero (which indicates that there is no orphan).

<DataGridTextColumn Header="Orphaned ID" Binding="{Binding OrphanedChangeID, StringFormat='{}{0:0;;#}'}"></DataGridTextColumn>


In this example, the format for negative numbers is not defined so it defaults to the format for positive numbers. The # symbol suppresses leading zeros - effectively leaving the column blank for zeros.





1 comment: