2016-07-31 2 views
0

사용자의 이름을 textBox에 입력해야하는 응용 프로그램을 만들고 있습니다. 나는 이것을하기 위해 튜토리얼을 버렸다. 그러나 textBox의 유효성을 검사하기 위해 버튼을 클릭하고 이름을 입력하지 않았 으면 "이름을 입력해야합니다."라는 확인 오류 메시지가 표시되지 않습니다. 대신 textBox에 텍스트를 입력하고 텍스트를 삭제 한 다음 버튼을 클릭하여 오류 메시지를 가져와야합니다. 나는 이것이 OnProperyChanged 방법을 사용했기 때문에 이것이라고 생각합니다. 텍스트를 먼저 입력 한 다음 텍스트를 삭제하지 않고도 textBox의 유효성을 검사 할 수있는 방법이 있습니까?텍스트 상자 유효성 검사 wpf

XAML

<TextBox.Text> 
     <Binding Path="Name" Mode="TwoWay" UpdateSourceTrigger="LostFocus"> 
      <Binding.ValidationRules> 
       <local:NameValidator></local:NameValidator> 
      </Binding.ValidationRules> 
     </Binding> 
    </TextBox.Text> 
</TextBox> 

NameValidator.cs

public class NameValidator : ValidationRule 
{ 
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) 
    { 
     if (value.ToString().Length ==0) 
      return new ValidationResult(false, "value cannot be empty."); 
     else 
     { 
      if (value.ToString().Length > 3) 
       return new ValidationResult(false, "Name cannot be more than 3 characters long."); 
     } 
     return ValidationResult.ValidResult; 
    } 
} 

xaml.cs

if (!Validation.GetHasError(tbxName)) 
      { 
       // do the proicessing 
      } 


private void OnPropertyChanged(string property) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs(property)); 
     } 

답변

0

텍스트 유효성 검사를 수행하는 매우 간단한 방법을 휴한지로

내 코드입니다 상자는 유효성 검사를 사용하는 것입니다. 규칙 기술 :

검증 예를 지배 :

public class NumericValidationRule : ValidationRule 
    { 
     public Type ValidationType { get; set; } 
     public override ValidationResult Validate(object value, CultureInfo cultureInfo) 
     { 
      string strValue = Convert.ToString(value); 

      if (string.IsNullOrEmpty(strValue)) 
       return new ValidationResult(false, $"Value cannot be coverted to string."); 
      bool canConvert = false; 
      switch (ValidationType.Name) 
      { 

       case "Boolean": 
        bool boolVal = false; 
        canConvert = bool.TryParse(strValue, out boolVal); 
        return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of boolean"); 
       case "Int32": 
        int intVal = 0; 
        canConvert = int.TryParse(strValue, out intVal); 
        return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Int32"); 
       case "Double": 
        double doubleVal = 0; 
        canConvert = double.TryParse(strValue, out doubleVal); 
        return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Double"); 
       case "Int64": 
        long longVal = 0; 
        canConvert = long.TryParse(strValue, out longVal); 
        return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Int64"); 
       default: 
        throw new InvalidCastException($"{ValidationType.Name} is not supported"); 
      } 
     } 
    } 

XAML :

매우 중요한 : ValidatesOnTargetUpdated는 = "참"은이 정의없이 작동하지 않습니다 설정하는 것을 잊지 마세요 .

<TextBox x:Name="Int32Holder" 
           IsReadOnly="{Binding IsChecked,ElementName=CheckBoxEditModeController,Converter={converters:BooleanInvertConverter}}" 
           Style="{StaticResource ValidationAwareTextBoxStyle}" 
           VerticalAlignment="Center"> 
          <!--Text="{Binding Converter={cnv:TypeConverter}, ConverterParameter='Int32', Path=ValueToEdit.Value, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"--> 
          <TextBox.Text> 
           <Binding Path="Name" 
             Mode="TwoWay" 
             UpdateSourceTrigger="PropertyChanged" 
             Converter="{cnv:TypeConverter}" 
             ConverterParameter="Int32" 
             ValidatesOnNotifyDataErrors="True" 
             ValidatesOnDataErrors="True" 
             NotifyOnValidationError="True"> 
            <Binding.ValidationRules> 
             <validationRules:NumericValidationRule ValidationType="{x:Type system:Int32}" 
                       ValidatesOnTargetUpdated="True" /> 
            </Binding.ValidationRules> 
           </Binding> 
          </TextBox.Text> 
          <!--NumericValidationRule--> 
         </TextBox> 
관련 문제