Building a Masked Currency TextBox in WPF

Written by

in

Formatting currency in a Windows Presentation Foundation (WPF) TextBox depends entirely on whether you want to format the value after editing or dynamically while typing.

The best approaches to achieve both patterns cleanly are outlined below.

1. The Cleanest Approach: Native XAML StringFormat (Format on Lost Focus)

If you only need the currency symbol, group separators, and decimals to appear once the user finishes editing, use native XAML binding with StringFormat=C.

To prevent the formatting from making it hard to type (e.g., trying to type digits alongside currency symbols in real-time), set the UpdateSourceTrigger to LostFocus.

Use code with caution.

Why it works: The standard “C” format specifier automatically adapts to the user’s system locale and language settings to choose the correct symbol (e.g., $, , ) and decimal rules.

Important Caveat: Ensure the underlying ViewModel property is a decimal or double data type. If it is bound to a string, StringFormat will be ignored. 2. The UX-Friendly Approach: Dual-Template Styling

A major drawback of using StringFormat inside a TextBox is that when a user clicks into the box to change a value, they are forced to delete or navigate around the formatted characters (like commas and dollar signs).

A smart, native XAML workaround changes the formatting dynamically based on whether the TextBox is focused.

Use code with caution.

How it works: When the user clicks the box, the currency symbol and commas disappear, leaving a clean, editable raw number. When they click away, it snaps back into a beautifully formatted currency string. 3. The Continuous Approach: Custom Behavior / Event Masking currency textbox on wpf c# – Stack Overflow

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *