2016-08-10 7 views
1

У меня есть объект CSLA с двумя управляемыми свойствами и обычным Attribute. Требования должны иметь как минимум одно свойство null.wpf поставщик ошибок не освежает

Другими словами: Если свойство A установлено в нечто, а свойство B уже имеет значение, тогда свойства A и B становятся недействительными. После свойства Бланкинга свойство А должно стать действительным и наоборот.

Для решения этой проблемы я вызвал Validator.ValidateProperty в настройщике свойств для проверки свойства A, когда B установлен и наоборот.

Проблема заключается в том, что поставщик ошибок не обновляется. Когда свойство А имеет значение и свойство обновляется, поставщик ошибок появляется вокруг двух полей, что совершенно нормально. При исключении свойства A поставщик ошибок уходит от txtBoxA и остается вокруг txtBoxB, хотя я вызвал проверку свойства B после того, как свойство A установлено. Обратите внимание, что во втором случае я пытаюсь изменить свойство B, поставщик ошибок исчезает. Я выгляжу так, как будто я не верю правильно.

Эта проблема сводит меня с ума. Я не уверен, что я делаю неправильно.

C#

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = true, Inherited = true)] 


     class CustomAttribute : ValidationAttribute 
     { 
     private readonly string _other; 
     public CustomAttribute(string other) 
      { 
      _other = other; 
      } 

     protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
      { 
      var property = validationContext.ObjectType.GetProperty(_other); 
      if (property == null) 
       { 
       return new ValidationResult(
        string.Format("Unknown property: {0}", _other) 
       ); 
       } 
      var otherValue = property.GetValue(validationContext.ObjectInstance, null); 

      if (!String.IsNullOrEmpty(value.ToString()) && !String.IsNullOrEmpty(otherValue.ToString())) 
       { 

       return new ValidationResult("At least on property has to be null !"); 
       } 
      return null; 
      } 
     } 




     public class Example : BusinessBase<Example> 
     { 
      public static PropertyInfo<string> AProperty = RegisterProperty<String>(p => p.A); 
     [CustomAttribute("B")] 
     public string A 
      { 
      get { return GetProperty(AProperty); } 
      set { SetProperty(AProperty, value); 

      if (B != "") 
        { 
        try 
         { 
         Validator.ValidateProperty(B, new ValidationContext(this) { MemberName = "B" }); 
         } 
        catch (Exception) 
         { 


         } 

        } 
       } 

      } 
     public static readonly PropertyInfo<string> BProperty = RegisterProperty<String>(p => p.B); 
     [CustomAttribute("A")] 
     public string B 
      { 
      get { return GetProperty(BProperty); } 
      set { SetProperty(BProperty, value); 

       if (A != "") 
        { 
        try 
         { 
         Validator.ValidateProperty(A, new ValidationContext(this) { MemberName = "A" }); 
         } 
        catch (Exception) 
         { 


         } 

        } 

       } 
      } 
     } 

МОФ #

<TextBox Name="txtBoxA" Width="300" Text="{Binding A, Mode=TwoWay, NotifyOnTargetUpdated=True, NotifyOnSourceUpdated=True, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" /> 
<TextBox Name="txtBoxB" Width="300" Text="{Binding B, Mode=TwoWay, NotifyOnTargetUpdated=True, NotifyOnSourceUpdated=True, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" /> 

ответ

1

Я решил проблему путем создания пользовательского CSLABusinessRule. А сделал два свойства зависимыми друг от друга.

Добавлен этот метод Пример класса Business Object #

using Csla; 
using Csla.Rules; 
using System; 
using System.ComponentModel.DataAnnotations; 

protected override void AddBusinessRules() 
{ 
BusinessRules.AddRule(new CustomBusinessRule(AProperty)); 
BusinessRules.AddRule(new CustomBusinessRule(BProperty)); 
BusinessRules.AddRule(new Csla.Rules.CommonRules.Dependency(AProperty, BProperty)); 
BusinessRules.AddRule(new Csla.Rules.CommonRules.Dependency(BProperty, AProperty)); 

} 

создания пользовательского правила

using System; 
using System.Collections.Generic; 
using Csla.Rules; 

public class CustomBusinessRule : BusinessRule 
     { 
     public OnlyOneOutPutLocationBusinessRule(Csla.Core.IPropertyInfo primaryProperty) : base(primaryProperty) 
      { 
      InputProperties = new List<Csla.Core.IPropertyInfo> { primaryProperty }; 
      } 
     protected override void Execute(RuleContext context) 
      { 
      Example target = (Example)context.Target; 
      if (!string.IsNullOrEmpty(ReadProperty(target, Example.A).ToString()) && !String.IsNullOrEmpty(ReadProperty(target, Example.B).ToString())) 
       { 
       context.AddErrorResult("At least on property has to be null !"); 

       } 
      } 
     } 

 Смежные вопросы

  • Нет связанных вопросов^_^