Search code examples
.netwpfvalidationpropertygrididataerrorinfo

Implementing validations in WPF PropertyGrid


I have implemented a PropertyGrid and properties of selected object(in another library) are displayed in it. Property values are bound to PropertyGrid controls through binding. Now, I want to perform validation on values user enters in PropertyGrid control(mainly TextBox) and display a message to user if value is not correct.

There will be some common validations like numeric values, required field etc and some business logic related validations(like value can't be more then this etc.).

What all approaches are available to implement this(IDataErrorInfo or something else)?


Solution

  • If you already have implemented IDataErrorInfo on your ViewModels, I found this data-template to be quite useful for displaying errors:

    <Style TargetType="{x:Type TextBox}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
            </Trigger>
        </Style.Triggers>
    </Style>
    

    That way, you only have to set ValidatesOnDataErrors=True on your textbox bindings and you get a tooltip displaying the error if anything is wrong. That can be applied to other controls as well.

    For information on how to implement IDataErrorInfo properly, look here:
    http://blogs.msdn.com/b/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx
    especially have a look at the section "3.5 IDataErrorInfo Support"