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>

示例代码

ValidationForm1

参考资料

ValidationRule 类
How to: Implement Binding Validation
How to disable a Button on TextBox ValidationErrors in WPF
Accessing WPF control validation rules from code

posted @ 2020-10-09 19:31  Lulus  阅读(582)  评论(0编辑  收藏  举报