Performing Group Validation

,

Validating a series of input fields usually entails validating each field as the user leaves the field, and then checking for completeness and validity of all fields when the Submit button is tapped (see Figure 26.7).

Image

FIGURE 26.7 Form validation activity diagram.

The UpdateSource method of the BindingExpression class can be used to validate all controls on a form. As you saw in the preceding section, the UpdateSource method causes the target value to be reassigned to its source property. In other words, the value in the control is pushed to its data context, allowing the discovery of any input validation errors.

The following excerpt from ConventionalValidationView.xaml.cs in the downloadable sample code demonstrates how to validate all TextBox fields on a form:

void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
    IEnumerable<TextBox> children = ContentPanel.GetDescendents<TextBox>();
    foreach (TextBox textBox in children)
    {
        BindingExpression bindingExpression
            = textBox.GetBindingExpression(TextBox.TextProperty);
        if (bindingExpression != null)
        {
            bindingExpression.UpdateSource();
        }
    }
}

The custom GetDescendents extension method recursively retrieves all children, children’s children, and so on, of a particular type for the specified FrameworkElement. The method is located in the VisualTree class in the downloadable sample code and is shown in the following excerpt:

public static IEnumerable<TChild> GetDescendents<TChild>(
    this FrameworkElement parent) where TChild : class
{
    ArgumentValidator.AssertNotNull(parent, "parent");

    int childCount = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < childCount; i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(parent, i);
        TChild candidate = child as TChild;
        if (candidate != null)
        {
            yield return candidate;
        }
        FrameworkElement element = child as FrameworkElement;
        if (element != null)
        {
            /* Could be improved with tail recursion. */
            IEnumerable<TChild> descendents
                        = element.GetDescendents<TChild>();
            foreach (TChild descendent in descendents)
            {
                yield return descendent;
            }
        }
    }
}

When the Submit button of the ConventionalValidationView page is tapped, all TextBoxes are retrieved and the UpdateSource method is called for each control’s Text property binding. If any input validation errors are present, they are displayed in the UI (see Figure 26.8).

Image

FIGURE 26.8 ConventionalValidationView page. Tapping the Submit button causes all fields to be validated.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.177.151