2010-11-25 17 views
16

XAML:Acceso WPF reglas de validación de control de código

 
    <TextBox Name="textboxMin"> 
     <TextBox.Text> 
      <Binding Path="Max"> 
       <Binding.ValidationRules> 
        <local:IntValidator/> 
       </Binding.ValidationRules> 
      </Binding> 
     </TextBox.Text> 
    </TextBox> 

Código:

 
void buttonOK_Click(object sender, RoutedEventArgs e) 
{ 
    // I need to know here whether textboxMin validation is OK 
    // textboxMin. ??? 

    // I need to write something like: 
    // if (textboxMin.Validation.HasErrors) 
    //  return; 
} 

Sería bueno también saber, cómo deshabilitar el botón Aceptar, si al menos uno de los controles de diálogo doesn pasar validación - en XAML, utilizando enlace. Teniendo esto en cuenta, no necesito verificar el estado de validación en el código.

+0

¿Necesita saber si un ReglaDeValidación específica tiene un error o simplemente si el cuadro de texto tiene errores? –

Respuesta

22

Validation.HasError es una propiedad adjunta para que pueda comprobar que textboxMin como esto

void buttonOK_Click(object sender, RoutedEventArgs e) 
{ 
    if (Validation.GetHasError(textboxMin) == true) 
     return; 
} 

Para ejecutar todas las ValidationRules para el TextProperty en código detrás se puede obtener el BindingExpression y llame UpdateSource

BindingExpression be = textboxMin.GetBindingExpression(TextBox.TextProperty); 
be.UpdateSource(); 

Actualización

Tomará algunos pasos para lograr el enlace para desactivar le el botón si ocurre alguna validación.

Primero, asegúrese de que todos los enlaces agreguen NotifyOnValidationError = "True". Ejemplo

<TextBox Name="textboxMin"> 
    <TextBox.Text> 
     <Binding Path="Max" NotifyOnValidationError="True"> 
      <Binding.ValidationRules> 
       <local:IntValidator/> 
      </Binding.ValidationRules> 
     </Binding> 
    </TextBox.Text> 
</TextBox> 

Luego conectamos un manejador de eventos al evento Validation.Error en la ventana.

<Window ... 
     Validation.Error="Window_Error"> 

Y en código detrás que añadir y eliminar los errores de validación en un ObservableCollection como vienen y vamos

public ObservableCollection<ValidationError> ValidationErrors { get; private set; } 
private void Window_Error(object sender, ValidationErrorEventArgs e) 
{ 
    if (e.Action == ValidationErrorEventAction.Added) 
    { 
     ValidationErrors.Add(e.Error); 
    } 
    else 
    { 
     ValidationErrors.Remove(e.Error); 
    } 
} 

Y entonces podemos obligar IsEnabled del botón para ValidationErrors.Count como esto

<Button ...> 
    <Button.Style> 
     <Style TargetType="Button"> 
      <Setter Property="IsEnabled" Value="False"/> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding ValidationErrors.Count}" Value="0"> 
        <Setter Property="IsEnabled" Value="True"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </Button.Style> 
</Button> 
+0

Primera versión - Validation.HasError no se compila. Después de la edición, GetHasError está bien y da el resultado esperado. Gracias. –

+0

Es mucho mejor usar AttachedProperty o Behavior para este propósito, pero gracias por mencionar NotifyOnValidationError se debe configurar como verdadero. –

6

que necesita para obtener la unión antes de obtener las reglas

Binding b= BindingOperations.GetBinding(textboxMin,TextBox.TextProperty); 
    b.ValidationRules 

cosa que se pueda tener BindingExpression y comprobar la propiedad hasError

BindingExpression be1 = BindingOperations.GetBindingExpression (textboxMin,TextBox.TextProperty); 

be1.HasError 
+1

BindingOperations.GetBindingExpression (textBoxMin, TextBox.TextProperty) .HasError hizo el truco. –

+0

Finalmente uso la versión corta Validation.GetHasError (textboxMin). Gracias. –

+0

¿Qué debería poner como propiedad si quiero verificar las vinculaciones de la cuadrícula de datos? p.ej. BindingOperations.GetBindingExpression (myDatagrid,?). HasError – DasDas

Cuestiones relacionadas