开发者

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 val开发者_StackOverflowues, 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)?


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"


I recently had to deal with this problem so I will post this example code to help others with the same problem.

using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

namespace ValidationExample
{

    public class SomeClass : DataErrorInfoImpl
    {
        [CustomValidation(typeof (SomeClassValidator), "ValidateSomeTextToValidate")]
        string SomeTextToValidate {get;set;}

    }

    public class SomeClassValidator
    {
        public static ValidationResult ValidateNumberOfLevelDivisons(string text)
        {
            if (text != "What every condition i want") return new ValidationResult("Text did not meet my condition.");
            return ValidationResult.Success;
        }

    }

    public class DataErrorInfoImpl : IDataErrorInfo
    {
        string IDataErrorInfo.Error { get { return string.Empty; } }

        string IDataErrorInfo.this[string columnName]
        {
            get
            {
                var pi = GetType().GetProperty(columnName);
                var value = pi.GetValue(this, null);

                var context = new ValidationContext(this, null, null) { MemberName = columnName };
                var validationResults = new List<ValidationResult>();
                if (!Validator.TryValidateProperty(value, context, validationResults))
                {
                    var sb = new StringBuilder();
                    foreach (var vr in validationResults)
                    {
                        sb.AppendLine(vr.ErrorMessage);
                    }
                    return sb.ToString().Trim();
                }
                return null;
            }
        }
    }
}

This style should work on WPF Xceed.PropertyGrid and WPF PropertyTools.PropertyGrid.


I recommend using IDataErrorInfo. That way, validation logic stays attached to ViewModel and not the UI. And WPF has well support for it as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜