We have seen Binding.StringFormat being used a million times with binding. But have you ever thought how to format the numbers when we need to show zero valued, negative and positive numbers separately. I saw someone using three different TextBlocks and using DataTrigger and similar logic to select based on the bound value. This code seems like too much for such a simple thing. So I thought about writing this post to share a simple solution to do the same.
As a matter of fact, the solution is not special to a WPF project. This can be used to format numeric values even in a non-WPF based applications. The idea is to use custom numeric formatting based on section separators.
Let's create a WPF project. We add a ViewModel to the project MainViewModel. It just has a property NumericProperty. The property is of integer type backed by an integer field.
Let's create a view with a TextBox and TextBlock. We need to view the formatted value in the TextBlock as entered in TextBox. But the requirement is that positive values should be shown as entered and negative values should be shown in a paranthesis. Zero value should be displayed as literal "ZERO" in the TextBlock.
Now let's have a look at the value of StringFormat specified for the TextBlock.Text binding. It uses section separators to declare format. Here are the three sections in the specified expression.
Now let's run the application. Here we enter zero, positive and negative values and see the expected result.
Here we don't have to specify all the sections. If we want to apply the same formatting for negatives and zero {0:#;(#)}, we can just use two sections. The formatting specified in the second section would be used in for both of them. If we want to use the same formatting for all positive and negative numbers and need to use a different one for zeros, we can leave the second section empty {0:#;;ZERO}.
In order to practice further with formatting, you can download this cool utility from Microsoft. The tool allows you to provide custom formatting and displays result so that you can test the expression before using it in your application. You can download the source code of the utility.
Monday, March 3, 2014
XAML - Conditional Formatting with Section Separators
Labels:
.net framework,
string.format,
StringFormat,
Tips Tricks,
wpf
Subscribe to:
Post Comments (Atom)
3 comments:
Nicely handled, Muhammad!
Nicely handled, Muhammad!
thx!
Post a Comment