简体   繁体   English

单击保存按钮触发表单验证规则

[英]Firing form validation rules on click of save button

I have a text box whose Text property is set like this: 我有一个文本框,其Text属性设置如下:

<TextBox.Text>
    <Binding Path="PointOfContact">
        <Binding.ValidationRules>
            <local:NotEmptyValidationRule />
        </Binding.ValidationRules>
    </Binding>
</TextBox.Text>

The NotEmptyValidationRule class looks like this: NotEmptyValidationRule类如下所示:

public class NotEmptyValidationRule : ValidationRule
{
    public string Message { get; set; }

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (string.IsNullOrWhiteSpace(value?.ToString()))
        {
            return new ValidationResult(false, Message ?? "A value is required");
        }
        return ValidationResult.ValidResult;
    }
}

Assuming there are several other controls on my form that have validation rules similarly-defined, how do I get the form to validate all of the rules on all of the controls when the Save button is clicked? 假设表单上还有其他几个控件具有类似定义的验证规则,那么当单击“保存”按钮时,如何获得表单来验证所有控件上的所有规则?

I have achieved this by implementing the INotifyDataErrorInfo interface on my model and mapping validation instances to properties. 我通过在模型上实现INotifyDataErrorInfo接口并将验证实例映射到属性来实现这一点。 On an attempted save if any of the validation checks fail you would invoke the event ErrorsChanged which would include the property name of whichever field was invalid. 尝试保存时,如果任何一项验证检查均失败,则将调用事件ErrorsChanged ,该事件将包括无效字段的属性名称。 You'll also have to set the flag ValidatesOnNotifyDataErrors to true on the binding. 您还必须在绑定上将标志ValidatesOnNotifyDataErrors设置为true。 I'm guessing you are hoping to do this without keeping separate instances of the validators but I'm not aware of another way. 我猜想您希望在不保留验证器单独实例的情况下执行此操作,但我不知道另一种方法。 You can also optionally remove the validator defined in the xaml as it's redundant. 您也可以选择删除xaml中定义的验证器,因为它是多余的。

<TextBox.Text>
  <Binding Path="PointOfContact">
    <Binding.ValidatesOnNotifyDataErrors>True</Binding.ValidatesOnNotifyDataErrors>
    <Binding.ValidationRules>
        <local:NotEmptyValidationRule />
    </Binding.ValidationRules>
  </Binding>
</TextBox.Text>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM