jeudi 17 janvier 2019

Validationrule for each property using reflection

I am thinking about using reflection in a ValidationRule. A user can enter values in a WPF DataGrid, while each cell of the DataGrid represents the properties of the underlying model (of course).

To avoid checking if a cell contains an invalid character (';') manually with an if statement for each cell (property) I intend to to that using reflection. ...but how can I get the type of the used class in the BindigGroup? Is that possible at all?

public class MyValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value,
        System.Globalization.CultureInfo cultureInfo)
    {
        BindingGroup group = (BindingGroup)value;
        StringBuilder error = null;
        foreach (var item in group.Items)
        {
            IDataErrorInfo info = item as IDataErrorInfo;
            if (info != null)
            {
                if (!string.IsNullOrEmpty(info.Error))
                {
                    if (error == null)
                    {
                        error = new StringBuilder();
                    }

                    Type type = typeof(MyClass);
                    PropertyInfo[] properties = type.GetProperties();
                    foreach (PropertyInfo property in properties)
                    {
                        Console.WriteLine(property.GetValue(property.Name, null));
                        if (property.GetValue(property.Name, null).ToString().Contains(";"))
                        {
                            error.Append(property.Name + " may not contain a ';'.");
                        }
                    }

                    error.Append((error.Length != 0 ? ", " : "") + info.Error);
                }
            }
        }

        if (error != null)
            return new ValidationResult(false, error.ToString());
        else
            return new ValidationResult(true, "");

    }
}





Aucun commentaire:

Enregistrer un commentaire