Assign Validators Dynamically from Code

Dec 10, 2008 at 3:16 PM

If it is possible, will you show a simple example of  how to add the validators in code. I imagine it to look something like this:

public
partial class Page : UserControl

 

{

 

ValidatorManager VM = new ValidatorManager();

 

 

public Page()

 

{

InitializeComponent();

Loaded +=

new RoutedEventHandler(Page_Loaded);

 

}

 

void Page_Loaded(object sender, RoutedEventArgs e)

 

{

 VM.Name =

"Group1";

 

sp.Children.Add(VM);

 

TextBox tb = new TextBox();

 

 

RequiredValidator rv = new RequiredValidator();

 

rv.ElementToValidate = tb;

rv.SetManagerAndControl(VM, tb);

sp.Children.Add(tb);

 }

 

}

 

Dec 13, 2008 at 7:38 AM

Try this...

  public partial class Page : UserControl

    {

        ValidatorManager validatorManager = new ValidatorManager();

        public Page()

        {           

            InitializeComponent();

 

            //Add a validator Manager

            validatorManager.Name = "validatorManager";

            LayoutRoot.Children.Add(validatorManager);

 

            //Add a stack panel

            StackPanel stackPanel = new StackPanel();

            LayoutRoot.Children.Add(stackPanel);

 

            //Add a text box

            TextBox firstNameTextBox = new TextBox();

            firstNameTextBox.Width = 100; firstNameTextBox.Height = 25;

            stackPanel.Children.Add(firstNameTextBox);

 

            //Add a submit button

            Button submitButton = new Button();

            submitButton.Width = 100; submitButton.Height = 25;

            submitButton.Content = "Submit";

            submitButton.Click += new RoutedEventHandler(submitButton_Click);

            stackPanel.Children.Add(submitButton);

 

            //Add a validator

            RequiredValidator firstNameValidator = new RequiredValidator();

            firstNameValidator.ElementToValidate = firstNameTextBox;

            firstNameValidator.ErrorMessage = "First name is required";

            firstNameValidator.ManagerName = "validatorManager";

            ValidatorService.SetValidator(firstNameTextBox, firstNameValidator);

        }

 

        void submitButton_Click(object sender, RoutedEventArgs e)

        {

            List<Silverlight.Validators.ValidatorBase> validators = validatorManager.ValidateAll();

            if (validators.Count > 0)

            {

                MessageBox.Show(validators.Count.ToString());

            }           

        }   

    }<!--EndFragment-->

Dec 15, 2008 at 4:42 PM
Edited Dec 15, 2008 at 4:43 PM
SoundScape:
Sweet. That works like a champ!