1. 程式人生 > 實用技巧 >WPF 驗證表單方法2

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