WPF 验证表单方法1
效果如图
验证表单的关键是使用ValidationRule
,官方资料:ValidationRule 类、How to: Implement Binding Validation
继承ValidationRule实现验证类
public class LengLimitValidationRule: ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
string str = value as string;
if (str != null)
{
if (!CanBeNull && str.Length == 0)
{
return new ValidationResult(false, CanNotBeNullMessage);
}
if (str.Length >= MinLength && str.Length <= MaxLength)
{
return ValidationResult.ValidResult;
}
if (str.Length > MaxLength)
{
return new ValidationResult(false, string.Format(MaxLengthMessage, MaxLength));
}
if (str.Length < MinLength)
{
return new ValidationResult(false, string.Format(MinLengthMessage, MinLength));
}
}
else
{
if (CanBeNull)
{
return ValidationResult.ValidResult;
}
else
{
return new ValidationResult(false, CanNotBeNullMessage);
}
}
return new ValidationResult(false, CanNotBeNullMessage);
}
public bool CanBeNull { get; set; }
public long MinLength { get; set; }
public long MaxLength { get; set; }
public String MinLengthMessage { get; set; }
public String MaxLengthMessage { get; set; }
public String CanNotBeNullMessage { get; set; }
}
为输入框添加验证
<Label Content="姓名"></Label>
<TextBox x:Name="nameTextBox" TextChanged="TextBox_TextChanged">
<TextBox.Text>
<Binding Path="Name" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
<Binding.ValidationRules>
<validations:LengLimitValidationRule ValidatesOnTargetUpdated="True"
CanBeNull="False"
CanNotBeNullMessage="必须填写姓名"
MinLength="2"
MaxLength="20"
MinLengthMessage="最小长度为{0}"
MaxLengthMessage="最大长度为{0}"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
监测输入行为,修改提交按钮可用性
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
ResetSubmitButton();
}
private void ResetSubmitButton()
{
var b1 = Validation.GetHasError(nameTextBox);
var b2 = Validation.GetHasError(ageTextBox);
var b3 = Validation.GetHasError(remarkTextBox);
submitButton.IsEnabled = !b1 && !b2 && !b3;
}
初始化的时候也要加上判断
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
ResetSubmitButton();
}
错误信息显示
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
示例代码
参考资料
ValidationRule 类
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】。
如果,你认为阅读这篇博客让你有些收获,不妨点击一下右下角的【推荐】按钮。
如果,你希望更容易地发现我的新博客,不妨点击一下【关注】。