【发布时间】:2014-01-08 19:36:56
【问题描述】:
我在 XAML 中定义了一个 WPF 文本框,如下所示:
<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>
如您所见,我的文本框绑定到名为 UpperLeftCornerLatitude 的业务对象上的小数属性,如下所示:
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);
}
}
我的文本框最初是空的,我在验证规则的开头设置了一个断点。我在文本框中输入 1,当我的调试器在验证规则内中断时,我可以看到 value = "1"。到目前为止,一切都很好。现在我继续运行并在文本框中输入一个小数点(所以我们现在应该有“1.”)。再次,调试器打破了验证规则,正如预期的那样,value = "1."。如果我单步执行验证规则代码,我会看到它通过了纬度值检查并返回以下内容:
new ValidationRule(true, null);
但是,一旦验证规则返回并进入下一行代码,我发现自己位于 UpperLeftCornerLatitude 属性设置器的第一行。将鼠标悬停在此处的 value 上表明它是“1”而不是“1”的值。正如我所料。所以很自然地,当我继续运行我的代码时,我最终会回到文本框中,盯着值“1”而不是“1.”。如果我删除所有断点,效果是我似乎无法在文本框中输入小数点。是否有一些明显的东西我在这里遗漏了,这导致我的设置器最终的值是“1”,即使我输入了“1”。在文本框中?非常感谢!
【问题讨论】:
-
跟ValidationRule没关系,跟Converter有关。当您键入“1”时。它无法将其解析为小数,因此它回退到“1”
标签: c# wpf validation textbox