1

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!

3 Answers 3

3

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"   />
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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!

6 Comments

-1 It is generally preferable not to leave such short answers with just a link in them on StackOverflow. You can find out more in the Answering section of the Help Center. I will remove this downvote if/when you update your answer.
Thanks for this precision, I'm sorry I did that mistake.
We all learn something new every day. As I said, if you edit your post by adding some context from your linked tutorial, then I can remove my down vote... I can't physically remove it until you make an edit though - it's not possible.
That's not really what I was talking about, but I'll remove the down vote for your effort. If you take a look at this post, you'll see that I have provided a link to a page that could help the question author, but I have also copied some of it into the answer to highlight the relevant part. Please see the Provide context for links section of the help pages for more information on this.
Thank you for the examples and taking the time to help meimprove my posts.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.