简体   繁体   English

Xceed WPF Propertygrid:在属性网格字段上进行验证

[英]Xceed WPF Propertygrid: Validation on Property grid fields

I am using Xceed's wpf property grid control to show some of my configuration properties. 我正在使用Xceed的wpf属性网格控件来显示一些配置属性。 I am doing via { SelectedObject="{Binding Entity.Configuration} } where Configuration object contains list of properties and this object is created at runtime using xml file. 我正在通过{ SelectedObject="{Binding Entity.Configuration} } ,其中Configuration对象包含属性列表,并且此对象是在运行时使用xml文件创建的。

I need to do validation on these properties (eg max/min values). 我需要对这些属性(例如最大/最小值)进行验证。 However I didn't find any way of doing validation. 但是我没有找到进行验证的任何方法。 Can anyone let me know if there is any? 有人可以让我知道吗?

Add the following to your class: 将以下内容添加到您的课程中:

using System.ComponentModel.DataAnnotations;

public class YourClass : DataErrorInfoImpl
{
    [Range(0, 100 , ErrorMessage = "The number must be from [0,100].")]
    Double SomeNumberToValidate {get;set;}

}

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;
        }
    }
}

Disclosure: I pulled some of this code out of propertytools property grid. 披露:我从propertytools属性网格中拉出了一些代码。 It works with both Xceed and PropertyTools library. 它与Xceed和PropertyTools库一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM