Powered by MSDN

US - English
NEW! Silverlight 5 is available Learn More

  • Sledge70

    Sledge70

    Star

    8044 Points

    1369 Posts

    Re: How to manually validate an object and have the results automatically added to a ValidationSu...

    Jul 20, 2009 11:38 PM | LINK

    The easiest way would be to update the bindingexpression for each property which will force validation to occur. A bit of a hack but saves you having to have your validation rules duplicated from your entity setter.

    This hack will loop through all children of an element and force validation. You could make this more generic but this should give you the idea of how to make it happen. Additionally you could throw in a call to Validation.GetErrors(uiElement) after bindingExpression.UpdateSource which will return any validation errors on the element. Handy if you want to manage your errors centrally with some other control etc.

    Have only tested this in Silverlight 3.

            ForceValidation(LayoutRoot.Children);

            private void ForceValidation(IEnumerable uiElements)
            {
                foreach (var uiElement in uiElements)
                {
                    BindingExpression bindingExpression = null;
                    
                    switch (uiElement.GetType().ToString())
                    {
                        case "System.Windows.Controls.StackPanel":
                        case "System.Windows.Controls.Panel":
                            ForceValidation(((Panel)uiElement).Children);
                            break;
    
                        case "System.Windows.Controls.TextBox":
                            bindingExpression = ((TextBox)uiElement).GetBindingExpression(TextBox.TextProperty);
                            break;
    
                        case "System.Windows.Controls.RadioButton":
                            bindingExpression = ((RadioButton)uiElement).GetBindingExpression(ToggleButton.IsCheckedProperty);
                            break;
                    }
    
                    if (bindingExpression == null || bindingExpression.ParentBinding == null) continue;
                    if (!bindingExpression.ParentBinding.ValidatesOnExceptions) continue;
    
                    bindingExpression.UpdateSource();
                }
            }

     

    Regards,