2010-08-16 7 views
2

모두 안녕 MVVM 모델을 사용하는 프로젝트를하고 있는데,이 모델에서 내 필드의 유효성을 검사 할 수있는 방법을 알려주는 사람이 누구든 도와 줄 수 있습니까? 유효성 검사는 이름 (예)이 사용자가 추가하지 않았 으면 팝업 메시지 나 다른 것을 사용하여 메시지를 표시하고 싶습니다 .Nolramlly는 함수를 작성하여이 작업을 수행했으며이 함수는 저장하기 전에 호출되거나 그 당시에는 Mandetory 필드 무료입니다 그때 만 오류가 표시됩니다, 그 필드를 채우고 난 후에 우리는 계속할 수 있습니다. 어떻게 MVVM 모델에서 이것을 할 수 있습니까?MVVM 모델에서 유효성 검사

답변

0

좋아요. 100 % 확신 할 수는 없지만 어디에서 가는지 예를 들어 보겠습니다. 이것이 MVVM에서 어떻게 작동할지는 모르지만 필자는 그렇게해야한다고 생각합니다.

public bool IsValid 
    { 
     get 
     { 
      return (GetRuleViolations().Count() == 0); 
     } 
    } 

    public override IEnumerable<RuleViolation> GetRuleViolations() 
    { 
     if (string.IsNullOrEmpty(Name)) 
      yield return new RuleViolation("Name can't be empty", "Name"); 

     else if (Name.Length >= 30) 
      yield return new RuleViolation("Name can't be more then 30 letters", "Name"); 

     if (!string.IsNullOrEmpty(Address)) 
     { 
      if (!Web.Contains("http")) 
       yield return new RuleViolation("Address must be bla bal", "Address"); 
     } 

     // and so on 

     yield break; 
    } 

을 그리고 RuleViolation 클래스를 만들 :

모델에서이 추가

public class RuleViolation 
{ 
    public string ErrorMessage { get; private set; } 
    public string PropertyName { get; private set; } 

    public RuleViolation(string errorMessage, string propertyName) 
    { 
     ErrorMessage = errorMessage; 
     PropertyName = propertyName; 
    } 
} 

을 지금 당신은 당신의 IsValid 방법은 모든 속성을 확인합니다를 호출 할 때. INotifyPropertyChanged를 사용하는 경우 유효성이 검사 된 속성을 업데이트 할 때마다 IsValid 속성을 업데이트 할 수 있습니다. 당신이 기본 모델 클래스가있는 경우는 거기를 추가하고 각 파생 클래스의 규칙을 정의 할 수 있습니다 :

public bool IsValid 
    { 
     get 
     { 
      return (GetRuleViolations().Count() == 0); 
     } 
    } 

    public abstract IEnumerable<RuleViolation> GetRuleViolations(); 

지금 질문은 당신이 당신의 UI에서이 오류를 표시 할 방법이다. UI가 무엇인지에 따라 다릅니다. WPF 응용 프로그램을 가정 해 보겠습니다. 그럼 당신은 IDataErrorInfo를 상속 모델을 필요로하고이처럼 사용할 수 있습니다

XAML 코드에서 다음
#region IDataErrorInfo Members 

    public string Error 
    { 
     get { return null; } 
    } 

    public string this[string name] 
    { 
     get 
     { 
      string result = null; 

      if (this.GetRuleViolations().Where(v => v.PropertyName == name).Count() > 0) 
      { 
       result = this.GetRuleViolations().Where(v => v.PropertyName == name).First().ErrorMessage; 
      } 

      return result; 
     } 
    } 

가 :

<TextBox Style="{StaticResource ValidationTextBox}" > 
        <TextBox.Text> 
         <Binding Path="Name" UpdateSourceTrigger="PropertyChanged"> 
          <Binding.ValidationRules> 
           <DataErrorValidationRule /> 
          </Binding.ValidationRules> 
         </Binding> 
        </TextBox.Text> 
       </TextBox> 

<Style x:Key="ValidationTextBox" TargetType="TextBox" > 
    <Setter Property="Validation.ErrorTemplate"> 
     <Setter.Value> 
      <ControlTemplate> 
       <Border BorderBrush="Red" BorderThickness="1"> 
        <AdornedElementPlaceholder /> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
    <Style.Triggers> 
     <Trigger Property="Validation.HasError" Value="true"> 
      <Setter Property="ToolTip" 
      Value="{Binding RelativeSource={RelativeSource Self}, 
        Path=(Validation.Errors)[0].ErrorContent}"/> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

당신이 UI로 Asp.net를 사용하는 경우가 일부에 내장되어 있습니다 거기에 양식에 오류를 표시하는 방법도 있습니다.

나는 더 나은 방법이있을 수 있지만 다소 도움이되기를 바랍니다.

+0

대단히 감사합니다. 어쨌든 이것을 구현하려고합니다. – user421678

+0

그래서 어떤 UI 구현을 사용하고 있습니까? –

관련 문제