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>

示例代码

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 20:11  Lulus  阅读(466)  评论(0编辑  收藏  举报