tags:

views:

33

answers:

3

Hi everyone,

During one of my project i need to add required field validation on the combo box of wpf application. in our process we are generating a form depending on the condition. after the form is generate and all of controls are rendered we need to implement the validation rule for the controls like for required text box i need to check whether this field is empty of not and on the combo box the validation will check for the selected index whether it is greater then 0 index.

i am searching for all above requirement but all of them are giving me the example of binding and applying validation rule in xaml file not in code file

how can i apply required field validation in text box , combo box, list box, and check box ?

A: 

This provides ValidationRule with C# example code. Also, this answer might help.

KMan
A: 

Hi,

If you dont want to use binding you can simple catch the LostFocus event and there implement your validation rules.

Iraklis
+1  A: 

You can set Binding in Code also.

1- Create a new validation rule class as shown below.

public class TextBoxEmptyRule : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        ValidationResult vr = new ValidationResult(true,null);
        if (string.IsNullOrEmpty(value))
        {
            vr.ErrorContent = " Value can not be null!";
            vr.IsValid = false;
        }
        return vr;


    }
}

2- While defining a new textbox , you can add binding at runtime as shown below.

        TextBox txt = new TextBox();

        Binding b = new Binding("Your Path Here");

        b.Source = "Your Source Here";

        b.ValidationRules.Add(new TextBoxEmptyRule());

        txt.SetBinding(TextBox.TextProperty, b);

3- You can add as many as rules to the binding.

4- Same can be added for combo box

saurabh
@Saurabh Thanks for reply in your case i need to create property first and then assign the path value to the binding class constructor then how to create property at runtime .
J S Jodha
@J S : You would know your Datasource in advance and which property you want to assign.
saurabh
@Saurabh every thing is fine for my work as your suggession but only one thing is missing for me i need to create a property for every control which is not possible for me . property we need to supply in the binding constructor
J S Jodha