Dilshod
Dilshod

Reputation: 3331

Creating WPF Validation error manually

I have a UI with some controls in it bound to Person class. Whenever user enters a new information business logic need to check the database if such a person exist. If not I need to give message to user and mark that textbox like it has error(red frame around the box). My Question is can I do that on the getter or setter of the property that gives Validation error?

Thanks for the help!

Upvotes: 1

Views: 1185

Answers (3)

HappyDump
HappyDump

Reputation: 453

I encountered kind of the same problem when learning to use Validations wit WPF I found help through this tutorial, hope it can help you too!

Upvotes: 0

Rajesh Subramanian
Rajesh Subramanian

Reputation: 6490

using IDataErrorInfo , you can do this as follows,

public class Person : IDataErrorInfo
{
    private int age;

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public string Error
    {
        get
        {
            return null;
        }
    }

    public string this[string name]
    {
        get
        {
            string result = null;

            if (name == "Age")
            {
                if (this.age < 0 || this.age > 150)
                {
                    result = "Age must not be less than 0 or greater than 150.";
                }
            }
            return result;
        }
    }
}

in XAML Binding as follows,

<Binding Source="{StaticResource data}" Path="Age"
                    UpdateSourceTrigger="PropertyChanged"
                    ValidatesOnDataErrors="True"   />

Upvotes: 3

Herm
Herm

Reputation: 2997

your VM should implement IDataErrorInfo and set ValidatesOnDataError=True in your Binding. Then you can validate in your ViewModel if such a person exists.

Upvotes: 0

Related Questions