Wednesday, March 5, 2014

Gotcha with StringFormat

Hope most of you have used StringFormat property on your binding to render the formatted value on the user interface. But are you aware about one of its secret. Well before revealing that secret, let’s have a look at how StringFormat works with binding.

Scenario problem: I am taking an example scenario, in which my text box will display amount till three decimals. 

Now there are multiple ways to achieve this. One way can be by using Converters, another way can be by using StringFormat along with TextBox binding. Perhaps there can be more ways apart from these two ;)

In below sample I am going to take StringFormat trick to achieve this and code to perform this operation is very straight forward as:

<TextBox Text="{Binding Amount,StringFormat=f3}" />

With above code, whenever you will lost focus from your TextBox, given amount will be displayed as three decimal points. Till here everything is perfect as expected BUT with one downsize.

Important point on StringFormat: 
What one sees on the screen is not the actual value that will be stored in the storage and can be different from the underlined value. But if this is really a requirement on what we want to show to the user then it’s up to developer to manage such inconsistencies.

Gotcha with StringFormat:
Now time came to know about that GOTCHA. If you want to add UpdateSourceTrigger property = PropertyChanged along with your StringFormat, then guess what will happen???

Code:
<TextBox  Text="{Binding Amount, UpdateSourceTrigger=PropertyChanged, StringFormat=f3}"/>

To understand this issue, let’s go step by step.
Step 1: Run the application and you will get below output.









Step 2: Enter value in the text box as 35.45. You will land up with below screen:









Explanation: Please note, you have applied UpdateSourceTrigger=PropertyChanged. So, as soon as you will hit a keyboard key, immediately StringFormat will be called due to change in target property and sets the underlined source property. Our source property raises a PropertyChanged event that forces the binding to re-bind and re-render based on the StringFormat. 

Problem occurs with fast input scenarios as shown in above screenshot and you will end up with RED rectangle.
Reason: After each key stroke, it is re-rendering the value of a given text box.

Step 3: Click on Save button in order to fire the loose focus from text box as shown below:









Explanation: As per the StringFormat property, given text box should be able to change the value to required precession. But it doesn’t happen. 
Reason: Due to UpdateSourceTrigger=PropertyChanged

One should avoid using UpdateSourceTrigger=PropertyChanged with StringFormat, due to this re-rendering issue.



No comments:

Post a Comment