WPF 验证表单方法2
示例来自How to disable a Button on TextBox ValidationErrors in WPF
效果如图
继承ValidationRule实现验证类
public class OverThirteenValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value != null)
{
int age = 0;
try
{
age = Convert.ToInt32(value);
}
catch
{
return new ValidationResult(false, "You must be older than 13!");
}
if (age > 13)
return ValidationResult.ValidResult;
}
return new ValidationResult(false, "You must be older than 13!");
}
}
通过MultiDataTrigger绑定提交按钮的IsEnabled属性
通过Path
获得每个输入框的Validation.HasError
值,当所有TextBox的HasError=false时,设置提交按钮可用
<Button Content="Submit" Name="buttonSubmit">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="IsEnabled" Value="false" />
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding ElementName=TextBoxFirstName, Path=(Validation.HasError)}" Value="false" />
<Condition Binding="{Binding ElementName=TextBoxLastName, Path=(Validation.HasError)}" Value="false" />
<Condition Binding="{Binding ElementName=TextBoxAge, Path=(Validation.HasError)}" Value="false" />
<Condition Binding="{Binding ElementName=TextBoxPhone, Path=(Validation.HasError)}" Value="false" />
</MultiDataTrigger.Conditions>
<Setter Property="IsEnabled" Value="true" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
显示提示信息
同样通过Validation.Errors
的值判断是否显示提示信息,这里用了一个Converter
(ToVisibility),判断错误信息个数是否为0,为0则不显示,不为0则显示
显示内容为(Validation.Errors)[0].ErrorContent
,即第一个错误内容,即如果有多个验证、有多个报错内容也只显示第一个
<TextBlock Visibility="{Binding ElementName=TextBoxAge, Path=(Validation.Errors), Converter={StaticResource ToVisibility}}">>
<TextBlock.Text>
<MultiBinding StringFormat="Age - {0}">
<Binding ElementName="TextBoxAge" Path="(Validation.Errors)[0].ErrorContent"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
示例代码
参考资料
How to: Implement Binding Validation
How to disable a Button on TextBox ValidationErrors in WPF
Accessing WPF control validation rules from code
学习技术最好的文档就是【官方文档】,没有之一。
还有学习资料【Microsoft Learn】、【CSharp Learn】、【My Note】。
如果,你认为阅读这篇博客让你有些收获,不妨点击一下右下角的【推荐】按钮。
如果,你希望更容易地发现我的新博客,不妨点击一下【关注】。