简体   繁体   English

WPF的CompareAttribute?

[英]CompareAttribute for WPF?

Does anyone know of a CompareAttribute data annotation for WPF, or a way of achieving the same result in WPF? 有人知道WPF的CompareAttribute数据注释,还是在WPF中获得相同结果的方法?

For those that don't immediately know, CompareAttribute is a property data annotation for validating in WPF, it takes a string for a second property and returns true if the decorated property and the passed property match. 对于那些尚不了解的对象,CompareAttribute是用于在WPF中进行验证的属性数据批注,它为第二个属性采用字符串,如果修饰的属性和传递的属性匹配,则返回true。

Basically I need to validate a password change form, to ensure the "retyped password" matches the new password, and do this with data annotations so that i can use the xaml validation template. 基本上,我需要验证密码更改表单,以确保“重新输入的密码”与新密码匹配,并使用数据注释进行此操作,以便我可以使用xaml验证模板。

您可以通过创建此处描述的自己的CustomValidationAttribute来创建自己的自定义验证逻辑。

Try Custom Validator like this 尝试像这样的Custom Validator

    public class EqualsValidationAttribute : ValidationAttribute
{
    string propertyToCompare;
    public EqualsValidationAttribute(string propertyToCompare)
    {
        this.propertyToCompare = propertyToCompare;
    }

    public EqualsValidationAttribute(string propertyToCompare,string errorMessage):this(propertyToCompare)
    {
        this.ErrorMessage = propertyToCompare;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var propInfo=validationContext.ObjectInstance.GetType().GetProperty(propertyToCompare);
        if (propInfo != null)
        {
            var propValue=propInfo.GetValue(validationContext.ObjectInstance);
            if(value!=null && propValue!=null && !string.IsNullOrEmpty(value.ToString()) && !string.IsNullOrEmpty(propValue.ToString()) //if either one is empty dont Validate
                && (value.ToString() != propValue.ToString()))
                return new ValidationResult(ErrorMessage);
        } 
        else
            throw new NullReferenceException("propertyToCompare must be the name of property to compare");

        return ValidationResult.Success;
    } 
}

and use it in Entity like this 并像这样在实体中使用

    [Required(ErrorMessage="Password Required")]
    public string Password {
        get { return password; }
        set { password = value; RaisePropertyChanged("Password"); }
    }

    [EqualsValidationAttribute("Password", ErrorMessage = "Confirm password must be same as password")]
    public string ConfirmPassword {
        get { return confirmedpassword; }
        set { confirmedpassword = value; RaisePropertyChanged("ConfirmPassword"); }
    }
}

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

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