I have a WPF textbox defined in XAML like this:
<Window.Resources>
<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<TextBox x:Name="upperLeftCornerLatitudeTextBox" Style="{StaticResource textBoxInError}">
<TextBox.Text>
<Binding Path="UpperLeftCornerLatitude" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:LatitudeValidationRule ValidationStep="RawProposedValue"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
private decimal _upperLeftCornerLongitude;
public decimal UpperLeftCornerLatitude
{
get { return _upperLeftCornerLongitude; }
set
{
if (_upperLeftCornerLongitude == value)
{
return;
}
_upperLeftCornerLongitude = value;
OnPropertyChanged(new PropertyChangedEventArgs("UpperLeftCornerLatitude"));
}
}
public class LatitudeValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
decimal latitude;
if (decimal.TryParse(value.ToString(), out latitude))
{
if ((latitude < -90) || (latitude > 90))
{
return new ValidationResult(false, "Latitude values must be between -90.0 and 90.0.");
}
}
else
{
return new ValidationResult(false, "Latitude values must be between -90.0 and 90.0.");
}
return new ValidationResult(true, null);
}
}
new ValidationRule(true, null);
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)
{
...
}
}