"复杂验证"使用INotifyDataErrorInfo和MVVM(MVVMLight)

时间:2014-03-25 03:24:37

标签: c# wpf mvvm mvvm-light inotifydataerrorinfo

基本上问题是我想在执行BL之前对从数据库(EF)获得的某些值执行验证。我目前正在使用带有ViewModel属性的属性的INotifyDataErrorInfo。我尝试使用自定义验证器(CustomValidation属性)进行此验证:

        private string unit;
        [Required(AllowEmptyStrings = false, ErrorMessage = Constants.Error6)]
        [RegularExpression(Constants.AlphabeticRegEx, ErrorMessage = Constants.Error10)]
        [CustomValidation(typeof(ProductSelectionViewModel),"IsInRegisteredUnits")]
        public string Unit
        {
            get { return unit; }
            set
            {
                if (value == unit)
                    return;
                unit = value;
                RaisePropertyChanged(vm => vm.Unit);
                UpdateUnitPrice(selectedProduct, unit);
            }
        }

但负责执行此验证的方法必须是静态的,因此在这种情况下我无法访问我的存储库,因为它不是静态的。

        public static ValidationResult IsInRegisteredUnits(object obj, ValidationContext context)
        {
            var productSelectionViewModel = (ProductSelectionViewModel)context.ObjectInstance;

            if (!unitService.GetAllUnitsAbbreviation().Any(x=>x.Equals(productSelectionViewModel.Unit, StringComparison.CurrentCultureIgnoreCase)))
                return new ValidationResult("La unidad ingresada no es válida", new List<string> { "Unit" });
            return ValidationResult.Success;
        }

我如何解决这个问题(unitService.GetAllUnitsAbbreviation()因为它使用存储库而不能是静态方法),也许我在worng地方执行这种验证(设计错误),任何帮助都会受到赞赏: )

0 个答案:

没有答案
相关问题