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