2011-05-27 18 views
11

Si tengo el siguiente cuadro de texto:WPF simple validación Pregunta - establecer ErrorContent encargo

<TextBox Height="30" Width="300" Margin="10" Text="{Binding IntProperty, 
     NotifyOnValidationError=True}" Validation.Error="ContentPresenter_Error"> 
</TextBox> 

Y esto en el código subyacente:

private void ContentPresenter_Error(object sender, ValidationErrorEventArgs e) { 
    MessageBox.Show(e.Error.ErrorContent.ToString()); 
} 

Si entro en la letra "x" en la casilla de texto , el mensaje que aparece es el valor

'x' no pudo ser convertido

¿Hay alguna manera de personalizar este mensaje?

+0

¿por qué no poner su propia cadena en el MessageBox.Show() ;? – Terrance

+0

Porque podría tener muchos otros cuadros de texto, y sería bueno tener un controlador de errores de validación que simplemente toma el contenido de error del último error de validación. –

Respuesta

10

me gusta responder a mi propia pregunta, pero parece que la única manera de hacer esto es poner en práctica un ReglaDeValidación, al igual que lo que está a continuación (puede haber algunos errores en ella):

public class BasicIntegerValidator : ValidationRule {  

    public string PropertyNameToDisplay { get; set; } 
    public bool Nullable { get; set; } 
    public bool AllowNegative { get; set; } 

    string PropertyNameHelper { get { return PropertyNameToDisplay == null ? string.Empty : " for " + PropertyNameToDisplay; } } 

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { 
     string textEntered = (string)value; 
     int intOutput; 
     double junkd; 

     if (String.IsNullOrEmpty(textEntered)) 
      return Nullable ? new ValidationResult(true, null) : new ValidationResult(false, getMsgDisplay("Please enter a value")); 

     if (!Int32.TryParse(textEntered, out intOutput)) 
      if (Double.TryParse(textEntered, out junkd)) 
       return new ValidationResult(false, getMsgDisplay("Please enter a whole number (no decimals)")); 
      else 
       return new ValidationResult(false, getMsgDisplay("Please enter a whole number")); 
     else if (intOutput < 0 && !AllowNegative) 
      return new ValidationResult(false, getNegativeNumberError()); 

     return new ValidationResult(true, null); 
    } 

    private string getNegativeNumberError() { 
     return PropertyNameToDisplay == null ? "This property must be a positive, whole number" : PropertyNameToDisplay + " must be a positive, whole number"; 
    } 

    private string getMsgDisplay(string messageBase) { 
     return String.Format("{0}{1}", messageBase, PropertyNameHelper); 
    } 
} 
+0

probablemente pueda aceptar su propia respuesta: busqué durante bastante tiempo pero no encontré otra solución que esta ... – stijn

+1

Así sea, al menos hasta que alguien venga con algo mejor :) –

4

Puede utilizar ValidationRules .

Por ejemplo, en mi caso, cuando un usuario introduce un valor no válido en una datagridtextcolumn decimal, en lugar del mensaje por defecto "Valor no podía ser convertido" Puedo anularlo con:

<DataGridTextColumn x:Name="Column5" Header="{x:Static p:Resources.Waste_perc}" Width="auto"> 
    <DataGridTextColumn.Binding> 
     <Binding Path="Waste" ValidatesOnDataErrors="True" UpdateSourceTrigger="LostFocus"> 
      <Binding.ValidationRules> 
       <myLib:DecimalRule /> 
      </Binding.ValidationRules> 
     </Binding> 
    </DataGridTextColumn.Binding> 
</DataGridTextColumn> 

y es aquí el código para el DecimalRule:

public override ValidationResult Validate(object value, CultureInfo cultureInfo) 
{ 
    decimal convertedDecimal; 
    if (!decimal.TryParse((string)value, out convertedDecimal)) 
    { 
     return new ValidationResult(false, "My Custom Message")); 
    } 
    else 
    { 
     return new ValidationResult(true, null); 
    } 
}