扩展方法实现DevExpress控件校验

DevExpress控件中,如果要控件的值进行校验,需要用到DXValidationProvider控件和DXErrorProvider控件,按照正常思路,无论使用哪个控件要实现校验效果时都需要对每个要校验的控件进行校验规则绑定,在这,写一个扩展方法实现一劳永逸的效果。

扩展代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using DevExpress.XtraEditors.DXErrorProvider;
    using System.Windows.Forms;
     
    namespace ValidateForm
    {
    ///<summary>
    ///验证值是否存在的验证规则
    ///</summary>
    public class CustomValidationRule : ValidationRule
        {
    public CustomValidationRule(Func<object, bool>validationFunction)
            {
    this.ValidateFunction = validationFunction;
            }
     
    ///<summary>
    ///获取或设置验证方法
    ///</summary>
    Func<object, bool>ValidateFunction { get; set; }
     
    ///<summary>
    ///验证待验证控件的值是否已存在
    ///</summary>
    ///<param name="control">待验证控件。</param>
    ///<param name="value">待验证控件的值</param>
    ///<returns>如果值已存在,返回false;否则返回true。</returns>
    public override bool Validate(System.Windows.Forms.Control control, object value)
            {
    if (this.ValidateFunction == null)
    throw new InvalidOperationException("必须设置ValidateFunction属性");
    return ValidateFunction(value);
            }
        }
     
    public static class DXValidationExtension
        {
     
    static Dictionary<int, Dictionary<int, List<DXValidationProvider>>>providerDictionary;
     
    static DXValidationExtension()
            {
    providerDictionary = newDictionary<int, Dictionary<int, List<DXValidationProvider>>>();
            }
     
    ///<summary>
    ///对控件容器中的待验证控件进行验证,并返回验证结果。
    ///</summary>
    ///<param name="container">控件容器</param>
    ///<returns></returns>
    public static bool DXValidate(this Control container)
            {
    bool isValid = true;//验证结果
     
    foreach (vardictinGetProviderDictionary(container))
                {
    foreach (var provider indict.Value)
                    {
    if (!provider.Validate())
                        {
    //任何一个未通过验证,则设置验证结果为false
    isValid = false;
    //待验证控件中的任何一个验证规则未通过,立即退出,不再验证该控件的其他规则
    break;
                        }
                    }
                }
    return isValid;
            }
     
    public static void CustomValidation(this Control container, Control controlToValidate, string errorText,
    Func<object, bool> validate)
            {
    CustomValidation(container, controlToValidate, errorText, validate, false, true);
            }
     
    private static void CustomValidation(this Control container, Control controlToValidate, string errorText, Func<object, bool> validate, bool alignRight, bool manualValidation)
            {
    //获得带验证的控件的DXValidationProvider集合。
    var dictionary = GetProviderDictionary(container);
    var providers = GetProvider(controlToValidate, dictionary);
    var provider = new DXValidationProvider();
    provider.ValidationMode = manualValidation ? ValidationMode.Manual : ValidationMode.Auto;
    provider.SetIconAlignment(controlToValidate, alignRight ? ErrorIconAlignment.MiddleRight : ErrorIconAlignment.MiddleLeft);
     
    provider.SetValidationRule(controlToValidate, newCustomValidationRule(validate)
                {
    ErrorText = errorText,
                });
     
    // 将DXValidationProvider添加到待验证控件的DXValidationProvider集合中。
    providers.Add(provider);
            }
     
    ///<summary>
    ///返回待验证控件的DXValidationProvider集合
    ///</summary>
    ///<param name="controlToValidate">待验证控件</param>
    ///<param name="dictionary">待验证控件所在的字典表</param>
    ///<returns></returns>
    private static List<DXValidationProvider>GetProvider(Control controlToValidate, Dictionary<int, List<DXValidationProvider>> dictionary)
            {
    var key = controlToValidate.GetHashCode();
    if (dictionary.ContainsKey(key))
    return dictionary[key];
    else
                {
    var providers = newList<DXValidationProvider>();
    dictionary.Add(key, providers);
    return providers;
                }
            }
     
    ///<summary>
    ///返回空间容器的待验证控件字典
    ///</summary>
    ///<param name="container"></param>
    ///<returns></returns>
    private static Dictionary<int, List<DXValidationProvider>>GetProviderDictionary(Control container)
            {
    var key = container.GetHashCode();
    if (providerDictionary.ContainsKey(key))
                {
    return   providerDictionary[key];
                }
    else
                {
    var providers = newDictionary<int, List<DXValidationProvider>>();
    providerDictionary.Add(key, providers);
    return providers;
                }
            }
        }
    }

 

程序调用代码示例如下:

    using System;
     
    using System.Collections.Generic;
     
    using System.ComponentModel;
     
    using System.Data;
     
    using System.Drawing;
     
    using System.Linq;
     
    using System.Text;
     
    using System.Threading.Tasks;
     
    using System.Windows.Forms;
     
    namespace ValidateForm
     
    {
     
    public partial class Form1 : Form
     
        {
     
    public Form1()
     
            {
     
    InitializeComponent();
     
    InitValidateRoles();
     
            }
     
    private void InitValidateRoles()
     
            {
     
    this.CustomValidation(calcEdit1, "请输入大于0小于20的值", value =>
     
                {
     
    returnConvert.ToInt32(calcEdit1.EditValue) >  &&Convert.ToInt32(calcEdit1.EditValue) <;
     
                });
     
            }
     
    private void simpleButton1_Click(object sender, EventArgs e)
     
            {
     
    if (!this.DXValidate())
     
    return;     
     
            }
     
        }
     
    }

 

posted @ 2019-09-08 19:05  青侠oO  阅读(781)  评论(0编辑  收藏  举报