简体   繁体   English

WPF-使用Fody Validar的用户输入验证

[英]WPF - User input validation using Fody Validar

在此处输入图片说明

I'm trying to validate user input as in above image. 我正在尝试验证用户输入,如上图所示。 I'm using Fody Validor library and following the instruction here . 我正在使用Fody Validor库,并按照此处的说明进行操作。

I can see the validation is taking place, but the TextBox borders are not turning into red color. 我可以看到验证正在进行中,但是TextBox边框没有变成红色。

I have Googled and I was unable to get information on this. 我已经用Google搜索,但无法获得有关此信息。 Could anyone provide me with a working code example? 谁能为我提供一个有效的代码示例?

UPDATE 更新

Fody ValidationTemplate (Data Annotation Validation) Fody ValidationTemplate(数据注释验证)

public class ValidationTemplate :IDataErrorInfo
    {

        INotifyPropertyChanged target;
        ValidationContext validationContext;
        List<ValidationResult> validationResults;

        public ValidationTemplate(INotifyPropertyChanged target)
        {
            this.target = target;
            validationContext = new ValidationContext(target, null, null);
            validationResults = new List<ValidationResult>();
            Validator.TryValidateObject(target, validationContext, validationResults, true);
            target.PropertyChanged += Validate;
        }

        void Validate(object sender, PropertyChangedEventArgs e)
        {
            validationResults.Clear();
            Validator.TryValidateObject(target, validationContext, validationResults, true);
            var hashSet = new HashSet<string>(validationResults.SelectMany(x => x.MemberNames));
            foreach (var error in hashSet)
            {
                OnValidate(error);
            }
        }


        private HashSet<string> _errors = new HashSet<string>();
        public string this[string columnName]
        {
            get
            {
                return OnValidate(columnName);
            }
        }

        protected virtual string OnValidate(string propertyName)
        {
            string error = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(propertyName))
                    throw new ArgumentException("Invalid property name", propertyName);

                var value = this.GetType().GetProperty(propertyName).GetValue(this, null);
                var results = new List<ValidationResult>(1);
                var context = new ValidationContext(this, null, null) { MemberName = propertyName };
                var result = Validator.TryValidateProperty(value, context, results);
                if (!result)
                {
                    var validationResult = results.First();
                    error = validationResult.ErrorMessage;
                    _errors.Add(propertyName);
                }
                else
                {
                    _errors.Remove(propertyName);
                }
            }
            catch (Exception) { }

            return error;
        }

        public bool HasErrors
        {
            get { return _errors.Count > 0; }
        }

        public string Error { get; set; }
    }

Model class to be validated: 要验证的模型类:

public class Movie :  INotifyPropertyChanged
    {
        IDataErrorInfo validationTemplate;
        public Movie()
        {
            validationTemplate = new ValidationTemplate(this);
        }

        private int _id;
        private string _title;
        public int Id
        {
            get { return _id; }
            set
            {
                if (_id != value)
                {
                    _id = value;
                    OnPropertyChanged("Id");
                }
            }
        }

        [Required]
        [StringLength(30)]
        [MinLength(3)]
        public string Title
        {
            get { return _title; }
            set
            {
                if (_title != value)
                {
                    _title = value;
                    OnPropertyChanged("Title");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }

XAML XAML

<TextBox Text="{Binding Movie.Title, Mode=TwoWay, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True, NotifyOnValidationError=True, ValidatesOnNotifyDataErrors=True, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" />

I have investigated and found the issue. 我已经调查并发现了问题。 The below configuration was missing in FodyWeavers.xml file. FodyWeavers.xml文件中缺少以下配置。

<?xml version="1.0" encoding="utf-8" ?>
<Weavers>
  <Validar/>
</Weavers>

The node <Validar/> was removed when i updated the Fody nuget package. 节点<Validar/>当我更新除去Fody NuGet包。

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

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