2016-07-31 20 views
0

Ich mache eine Anwendung, wo der Name des Benutzers in eine textBox eingegeben werden muss. Ich habe dazu ein Tutorial erstellt. Wenn ich jedoch auf die Schaltfläche klicke, um die textBox zu validieren, und ich habe keinen Namen eingegeben, bekomme ich keinen Validierungsfehler, der sagt "Name muss eingegeben werden". Stattdessen muss ich Text in die textBox eingeben und dann den Text löschen und dann auf den Button eine Fehlermeldung erhalten. Ich denke, das ist, weil ich es mit einer OnProperyChanged Methode gemacht habe. Gibt es eine Möglichkeit, meine textBox zu validieren, ohne zuerst Text eingeben zu müssen und dann den Text zu löschen?Validierung eines Textfelds wpf

Mein Code ist wie

XAML

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

NameValidator.cs Bricht

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)); 
     } 

Antwort

0

Die sehr einfache Art und Weise der Validierung auf Text zu tun Box ist mit Validaton Regeltechnik:

Gültigkeitsregel Beispiel:

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:

Sehr wichtig: Vergessen Sie nicht zu setzen ValidatesOnTargetUpdated = "True" wird es nicht ohne diese Definition arbeiten .

<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>