Here is my textbox xaml
<TextBox HorizontalAlignment="Left" TextWrapping="NoWrap" Text="{Binding Path=PointChangeRate,UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True,TargetNullValue='', StringFormat=D}" VerticalAlignment="Center" Margin="10" Grid.Column="1" Grid.Row="1" Width="160" Height="24"/>
Here is my propery in view model
[Required(ErrorMessage = "PointChangeRate is Required")]
[RegularExpression("^[0-9]{1,5}([.][0-9]{1,5})?$", ErrorMessage = "PointChangeRate cannot have more than 5 decimal points")]
[CustomValidate(GroupID = "PointCalculationSettings")]
public Nullable<double> PointChangeRate
{
get
{
return this._trackingConfig.PointChangeRate;
}
set
{
this._trackingConfig.PointChangeRate = value;
OnPropertyChanged("PointChangeRate");
}
}
The thing is the property in the view model gets updated for the first key press(checked it with a breakpoint in set). However the textbox is set to the value only on second key press. This happens only for the very first time while the Property is null.
The problem doesn't persit say when i use backspace to clean the text and then start typing all over again. Quite Wierd!
I bothered to set the string format to 'D' so that i can allow a user to enter the '.' value in the textbox.
I found some alternative as mentioned below. but the workaround doesn't seem convincing TextBox Won't Allow me to enter in a decimal
If you check the Debug Output in Visual Studio you can see the following error message after trying to enter the first digit:
System.Windows.Data Error: 6 : 'StringFormat' converter failed to convert value '5' (type 'Double'); fallback value will be used, if available. BindingExpression:Path=PointChangeRate; DataItem='MainWindow' (Name=''); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') FormatException:'System.FormatException: Format specifier was invalid.
If you check the documentation for Decimal ("D") Format Specifier it clearly states that:
This format is supported only for integral types.
Your property in the view model is of type double?
(Nullable<double>
) which is not an integral type.
So I think the usage of D
in the StringFormat
is erroneous here.
Setting a Delay
on the binding is not a bad solution though as quoted in the other answer. That will give time for the user to actually type in another digit after pressing the period.
What happens in your case is exactly this.