adminSoftDK
adminSoftDK

Reputation: 2092

Wpf Data annotation validation required, when the textbox is first created then validation does not work until something is typed in

I am using validation in my wpf xaml project with ValidationContext, which then looks up data annotation. It all works great, I get a red box around a texblock and a tooltip from a style. However there are two things I cannot work out, when a user opens a view, which has a field that is required I want that texblock to have a red box around immediately. Instead of getting it, after I typed in and then remove some text in to texbox that is bound to a required. How do I make it validate on start? Here is some code:

    protected void ValidateProperty(object value, [CallerMemberName] string propertyName = "")
    {
        var context = new ValidationContext(this, null, null) {MemberName = propertyName};
        Validator.ValidateProperty(value, context);
    }

    [Required(ErrorMessage = ErrorMessages.DescriptionRequired)]
    [StringLength(60, ErrorMessage = ErrorMessages.DescriptionLength60)]
    public string Description
    {
        get { return description; }
        set
        {
            description = value;
            ValidateProperty(value);
            OnPropertyChanged();
        }
    }


    <TextBox x:Name="DescriptionTextBox"
             Text="{Binding SelectedEntity.Description,
                            ValidatesOnExceptions=True, UpdateSourceTrigger=PropertyChanged}"/>

So I want the DescriptionTextBox to be red by default because when the user creates new description the textbox is empty.

My Second question is about the data annotation can I set the length of DescriptionTextBox to be whatever the length of the string is in the data annotation?

Kind Regards

Daniel

Upvotes: 1

Views: 1046

Answers (1)

Mike Strobel
Mike Strobel

Reputation: 25623

You cannot validate the initial source value with exception-based validation, as that requires calling the property setter. You can, however, use a different validation mechanism like IDataErrorInfo (implement the interface and set ValidatesOnDataErrors=True on your bindings). This mechanism allows for validation to occur on the initial source value.

If your app requires .NET 4.5, then you can alternatively use INotifyDataErrorInfo (w/ ValidatesOnNotifyDataErrors=True on your bindings).

Upvotes: 2

Related Questions