Alex Rivera | Logout

How can I format a decimal bound to TextBox without angering my users?

Asked 2012-07-13T20:21:52.317
52

I'm trying to display a formatted decimal in a TextBox using data binding in WPF.

Goals

Goal 1: When setting a decimal property in code, display 2 decimal places in the TextBox.

Goal 2: When a user interacts with (types in) the TextBox, don't piss him/her off.

Goal 3: Bindings must update source on PropertyChanged.

Attempts

Attempt 1: No formatting.

Here we're starting nearly from scratch.

<TextBox Text="{Binding Path=SomeDecimal, UpdateSourceTrigger=PropertyChanged}" />

Violates Goal 1. SomeDecimal = 4.5 will show "4.50000" in the TextBox.

Attempt 2: Use StringFormat in the Binding.

<TextBox Text="{Binding Path=SomeDecimal, UpdateSourceTrigger=PropertyChanged, StringFormat=F2}" />

Violates Goal 2. Say SomeDecimal is 2.5, and the TextBox is displaying "2.50". If we select all and type "13.5" we end up with "13.5.00" in the TextBox because the formatter "helpfully" inserts decimals and zeros.

Attempt 3: use Extended WPF Toolkit's MaskedTextBox.

http://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox

Assuming I'm reading the documentation correctly, the mask ##0.00 means "two optional digits, followed by a required digit, a decimal point, and two more required digits. This forces me to say "the largest possible number that can go into this TextBox is 999.99" but let's say I'm ok with that.

<xctk:MaskedTextBox Value="{Binding Path=SomeDecimal, UpdateSourceTrigger=PropertyChanged}" Mask="##0.00" />

Violates Goal 2. The TextBox starts with ___.__ and selecting it and typing

Edit
Report

1 Answer

1

Try the WPF Extended Tookit Masked TextBox to implement an Input Mask: http://wpftoolkit.codeplex.com/wikipage?title=MaskedTextBox

Example:

<toolkit:MaskedTextBox Mask="(000) 000-0000" Value="(555) 123-4567" 
IncludeLiterals="True" />
answered 2012-07-13T20:57:58.767

Your Answer