繁体   English   中英

通过属性进行WPF验证检查属性是否有效

[英]WPF validation by attributes check if property is valid

我的C#WPF应用程序中有一个ViewModel ,它包含几个像这样的属性

public class ExecutionsCreateViewModel : ValidationViewModelBase
{
    [Required(ErrorMessage = "Execution name is required.")]
    [StringLength(60, ErrorMessage = "Execution name is too long.")]
    public string ExecutionName { get; set; }
    [...]
}

这是我的ValidationViewModelBase

public abstract class ValidationViewModelBase : IDataErrorInfo
{
    string IDataErrorInfo.Error
    {
        get
        {
            throw new NotSupportedException("IDataErrorInfo.Error is not supported.");
        }
    }
    string IDataErrorInfo.this[string propertyName]
    {
        get
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                throw new ArgumentException("Invalid property name", propertyName);
            }
            string error = string.Empty;
            var value = GetValue(propertyName);
            var results = new List<ValidationResult>(1);
            var result = Validator.TryValidateProperty(
                value,
                new ValidationContext(this, null, null)
                {
                    MemberName = propertyName
                },
                results);
            if (!result)
            {
                var validationResult = results.First();
                error = validationResult.ErrorMessage;
            }
            return error;
        }
    }
    private object GetValue(string propertyName)
    {
        PropertyInfo propInfo = GetType().GetProperty(propertyName);
        return propInfo.GetValue(this);
    }
}

这是我在XAML中的TextBox

<TextBox Text="{Binding ExecutionName, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnExceptions=True, ValidatesOnDataErrors=True}"/>

属性正在运行,当属性变为无效时会正确通知UI(触发“无效” VisualState )。

问题是,如果某些属性当前有效,我不知道如何检查Create方法。

private void Create()
{
    if(/*check if property is invalid*/)
    {
        MessageBox.Show(/*property ErrorMessage*/);
        return;
    }

    //Do something with valid properties
}}

我试着Validator.ValidateProperty123 ),但它不工作和/或它的太乱了。 我也在做伎俩

    try
    {
        ExecutionName = ExecutionName;
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
        return;
    }

但它在某些情况下不起作用,看起来不太专业。 也许ValidateProperty是关键,但经过许多“教程”后,我仍然不知道如何满足我的需求。

还有第二件小事。 属性总是验证其属性,因此当用户收到新表单时, ExecutionName将始终为null,因此Required属性将其标记为无效,因此控件将自动变为红色。 有没有办法在初始化时跳过验证?

问题是,如果某些属性当前有效,我不知道如何检查Create方法。

ValidationViewModelBase类中的方法相同,例如:

private void Create()
{
    var value = this.ExecutionName; //the property to validate
    var results = new List<ValidationResult>();
    var result = Validator.TryValidateProperty(
        value,
        new ValidationContext(this, null, null)
        {
            MemberName = "ExecutionName" //the name of the property to validate
        },
        results);

    if (!result)
    {
        var validationResult = results.First();
        MessageBox.Show(validationResult.ErrorMessage);
    }

    //...
}

暂无
暂无

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

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