2014-01-15 3 views
4

나는 WPF 응용 프로그램에 체크 상자와 텍스트 상자가있는 UI가 있습니다. 확인란과 텍스트 상자는 내 비즈니스 개체의 속성에 바인딩됩니다. 나는 유효성 검사 규칙을 사용하여 사용자 입력의 유효성을 검증 해 왔으며, 대부분의 경우 값이 null/empty가 아닌지 확인하고 값이 특정 범위 내에 있는지 확인하는 등 매우 간단합니다. FWIW, 여기에 기존 XAML의 :WPF의 텍스트 상자에 대한 조건부 유효성 검사 규칙은 무엇입니까?

<StackPanel> 
    <CheckBox x:Name="requirePinNumberCheckBox" IsChecked="{Binding Path=RequirePinNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">Require PIN number</CheckBox> 
    <TextBox x:Name="pinNumberTextBox" Style="{StaticResource textBoxInError}" PreviewTextInput="pinNumberTextBox_PreviewTextInput"> 
     <TextBox.Text> 
      <Binding Path="PinNumber" Mode="TwoWay" UpdateSourceTrigger="LostFocus"> 
       <Binding.ValidationRules> 
        <local:PinNumberValidationRule ValidationStep="RawProposedValue"/> 
       </Binding.ValidationRules> 
      </Binding> 
     </TextBox.Text> 
    </TextBox> 
</StackPanel> 

텍스트 상자에 대한 나의 유효성 검사 규칙은 간단하다 :

내 다른 검증 대부분의 시나리오와는 달리
public class PinNumberValidationRule : ValidationRule 
{ 
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) 
    { 
     // make sure that the PIN number isn't blank 
     if (string.IsNullOrEmpty(value.ToString())) 
     { 
      return new ValidationResult(false, "PIN number cannot be blank."); 
     } 
     else 
     { 
      return new ValidationResult(true, null); 
     } 
    } 
} 

, 텍스트 상자의 ValidationRule는 는 경우에 적용해야 확인란이 선택되어 있는지 확인합니다 (또는 확인란이 바인딩 된 부울 속성이 TRUE로 설정된 경우). 아무도 이런 식으로 뭔가를 구현하는 방법을 말해 줄래? 감사!

답변

7

당신은 UI (ValidationRule)에서 멀리 떨어진 유효성 검사 논리를 이동하고 뷰 모델에 IDataErrorInfo을 구현하는 것을 고려해야 할 것이다.

좋은 시작은 this article입니다.

<StackPanel> 
    <CheckBox x:Name="requirePinNumberCheckBox" IsChecked="{Binding Path=RequirePinNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">Require PIN number</CheckBox> 
    <TextBox x:Name="pinNumberTextBox" 
      PreviewTextInput="pinNumberTextBox_PreviewTextInput" 
      Text="{Binding PinNumber, ValidatesOnDataErrors=True}" 
      ToolTip="{Binding (Validation.Errors).CurrentItem.ErrorContent, RelativeSource={RelativeSource Self}}" /> 
</StackPanel> 
public class ViewModel : IDataErrorInfo, INotifyPropertyChanged 
    { 
      private bool _requirePinNumber; 
      public bool RequirePinNumber 
      { 
       get 
       { 
        return this._requirePinNumber; 
       } 
       set 
       { 
        this._requirePinNumber = value; 
        if (this.PropertyChanged != null) 
        { 
         this.PropertyChanged(this, new PropertyChangedEventArgs("RequirePinNumber")); 
         this.PropertyChanged(this, new PropertyChangedEventArgs("PinNumber")); 
        } 
       } 
      } 

      private string _pinNumber; 
      public string PinNumber 
      { 
       get 
       { 
        return this._pinNumber; 
       } 
       set 
       { 
        this._pinNumber = value; 
        if (this.PropertyChanged != null) 
        { 
         this.PropertyChanged(this, new PropertyChangedEventArgs("PinNumber")); 
        } 
       } 
      } 

      public string Error 
      { 
       get 
       { 
        throw new NotImplementedException(); 
       } 
      } 

      public string this[string columnName] 
      { 
       get 
       { 
        if (columnName == "PinNumber") 
        { 
         if (this.RequirePinNumber && string.IsNullOrEmpty(this.PinNumber)) 
         { 
          return "PIN number cannot be blank."; 
         } 
        } 
        return string.Empty; 
       } 
      } 

      public event PropertyChangedEventHandler PropertyChanged; 
     } 
:

그런 다음 당신이 뭔가를 할 수 있습니다

1

이전 버전 인 ValidationRule을 잊어 버리고 컨트롤 대신 데이터 유효성 검사를 시작하십시오. 자세한 내용은 MSDN의 IDataErrorInfo Interface 또는 INotifyDataErrorInfo Interface 페이지를 살펴보십시오. 이러한 인터페이스를 사용하면 유효성 검사 코드를 데이터 클래스로 옮길 수 있습니다.

public override string this[string propertyName] 
{ 
    get 
    { 
     string error = string.Empty; 
     if (propertyName == "PinNumber" && RequirePinNumber && 
      string.IsNullOrEmpty(PinNumber)) 
       error = "You must enter the PinNumber field."; 
     ... 
     return error; 
    } 
} 
관련 문제