WPF validation rule preventing decimal entry in textbox?
.NET 4.5 UPDATE
In .NET 4.5, Microsoft decided to introduce a breaking change to the way that data is entered into the TextBox
control when the binding UpdateSourceTrigger
is set to PropertyChanged
. A new KeepTextBoxDisplaySynchronizedWithTextProperty
property was introduced that was supposed to recreate the previous behaviour... setting it to false
should return the previous behaviour:
FrameworkCompatibilityPreferences.KeepTextBoxDisplaySynchronizedWithTextProperty = false;
Unfortunately, although it allows us to enter a numerical separator again, it doesn't quite work as it used to. For example, the separator will still not appear in the TextBox.Text
property value until it is followed by another number and this can cause issues if you have custom validation. However, it's better than a slap in the face.
Here are a few ways to fix this problem
A. Specify LostFocus (textbox default) for your binding
<Binding Path="UpperLeftCornerLatitude" Mode="TwoWay" UpdateSourceTrigger="LostFocus">
</Binding>
B. Specify a Delay
for the binding that will allow for some time for you to type the decimal
<Binding Path="UpperLeftCornerLatitude" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" Delay="1000">
</Binding>
C. Change decimal
to string
and parse it yourself
D. Write a ValueConverter
to override the default conversion process
class DecimalConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
...
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
...
}
}