您可以将验证规则附加到文本框的绑定中,以检查该值是否为有效的双精度值。这将阻止用户按下提交按钮,除非输入了有效值,从而无需在提交时检查 DoubleProperty 值是否有效,因为它仅在启用提交按钮时才有效。这是一个简单的例子:
<TextBox HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="120">
<TextBox.Text>
<Binding Path="DoubleProperty">
<Binding.ValidationRules>
<validationrules:NumberValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
在上面的示例中,您需要定义一个继承 ValidationRule 的类 NumberValidationRule。
这是一个示例 NumberValidationRule
public class NumberValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
double result = 0.0;
bool canConvert = double.TryParse(value as string, out result);
return new ValidationResult(canConvert, "Not a valid double");
}
}
添加验证规则后,如果您的 ValidationRule 类说它不是有效值,文本框将在文本字段上引发错误。
要防止启用提交按钮,您可以向其添加 CanExecute 事件,以检查 wpf 窗口是否有效。像这样:
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Save" CanExecute="Save_CanExecute" Executed="Save_Executed"/>
</Window.CommandBindings>
... The rest of your page
<Button Content="Save" HorizontalAlignment="Left" Margin="43,146,0,0" VerticalAlignment="Top" Width="75" Command="ApplicationCommands.Save"/>
在后面的代码中
private void Save_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = IsValid(sender as DependencyObject);
}
private bool IsValid(DependencyObject obj)
{
return !Validation.GetHasError(obj) && LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>().All(IsValid);
}
这里有一个更详细的例子:
Validation in WPF