2016-07-31 101 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

很簡單的方式做文字驗證框是通過使用Validaton規則技巧:

驗證規則例如:

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>