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

时间:2017-09-13 12:36:34

标签: c# wpf validation xaml

我的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属性会将其标记为无效,因此控件将自动变为红色。有没有办法在初始化时跳过验证?

1 个答案:

答案 0 :(得分:3)

  

问题是,如果某些属性目前有效,我不知道如何检查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); } //... } 方法。

与您在{{1}}课程中的方式相同,例如:

{{1}}
相关问题