WPF TextBox Binding with Formatting

bindingstring-formattingwpf

I have just upgraded our wpf application from 3.5sp1 to 4.0.

The code below we use to bind the textbox to the underlying view model. The textbox is editable.

    <TextBox HorizontalContentAlignment="Right"
Text="{Binding Path=Price,   StringFormat={0:#,##0;(#,##0)},  Mode=TwoWay,  ValidatesOnDataErrors=True,  UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}"/>

In 3.5sp1 the formatting would only occur initially. So when the textbox was loaded and bound to value 4000, the formatting would change it to 4,000. If user edited this value no formatting would occur.

In 4.0 the formatting occurs as the value changes (ie while user enters in new value). While in theory this sounds OK, in reality its a disaster. The cursor is all over the place. Its unusable.

Now, we could change the UpdateSourceTrigger to "LostFocus" but that introduces new problems with data not being validated in certain scenarios.

Is there a way to get the old 3.5sp1 behaviour back?

Update 1

Using Converter still procudes same behaviour:

public class DecimalConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null)
            return ((decimal)value).ToString("#,##0;(#,##0)");

        return string.Empty;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}

and the modified XAML:

<TextBox Text="{Binding Path=Price, Converter={StaticResource DecimalConverter}, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}"/>

Update 2

Similar to this connect article.

Best Answer

As an update I took Jonathans suggestion and rejigged the Binding to use LostFocus instead of PropertyChanged (where appropriate - ie wherever StringFormat was also specified).

As Jonathan said, in some cases you have to trigger binding refresh / validation manually taking this approach.

If anyone has better approach, I would love to see it.

Related Topic