如何在MVVM中捕获DataAnnotations验证

时间:2012-10-30 10:14:45

标签: c# validation mvvm attributes data-annotations

如何从DataAnnotations中捕获验证? 我在这里研究,但我不明白它是如何工作的

所以我跳了一些你可以启发我的

这是我目前的测试代码:

模型

public class Person // Represents person data.
{
    /// <summary>
    /// Gets or sets the person's first name.
    /// </summary>
    /// <remarks>
    /// Empty string or null are not allowed.
    /// Allow minimum of 2 and up to 40 uppercase and lowercase.
    /// </remarks>
    [Required]
    [RegularExpression(@"^[a-zA-Z''-'\s]{2,40}$")]        
    public string FirstName{ get; set;}

    /// <summary>
    /// Gets or sets the person's last name.
    /// </summary>
    /// <remarks>
    /// Empty string or null are not allowed.
    /// </remarks>
    [Required]
    public string LastName { get; set;}

    public int Age{ get; set;}
}

视图

<Window x:Class="DataAnnotationstest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DataAnnotationstest"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:Person FirstName="Tomer" LastName="Shamam" />
    </Window.DataContext>
    <Grid>
        <StackPanel Margin="4,4,51,4">
            <TextBox Text="{Binding FirstName, ValidatesOnDataErrors=True}" />
            <TextBox Text="{Binding LastName, ValidatesOnDataErrors=True}" />
            <TextBox Text="{Binding Age, ValidatesOnDataErrors=True}" />
        </StackPanel>
    </Grid>
</Window>

我需要为Person实现其他功能吗? 我发现here下面的代码,但就像我之前所说的那样,我不明白它是怎么回事--.-

public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
    var attrType = typeof(T);
    var property = instance.GetType().GetProperty(propertyName);
    return (T)property .GetCustomAttributes(attrType, false).First();
}

1 个答案:

答案 0 :(得分:7)

解决方案

public class Person : IDataErrorInfo // Represents person data.
{
    /// <summary>
    /// Gets or sets the person's first name.
    /// </summary>
    /// <remarks>
    /// Empty string or null are not allowed.
    /// Allow minimum of 2 and up to 40 uppercase and lowercase.
    /// </remarks>
    [Required]
    [RegularExpression(@"^[a-zA-Z''-'\s]{2,40}$")]        
    public string FirstName{ get; set;}

    /// <summary>
    /// Gets or sets the person's last name.
    /// </summary>
    /// <remarks>
    /// Empty string or null are not allowed.
    /// </remarks>
    [Required]
    public string LastName { get; set;}

    public int Age{ get; set;}

    public string Error // Part of the IDataErrorInfo Interface
    {
        get { throw new NotImplementedException(); }
    }

 string IDataErrorInfo.this[string propertyName] // Part of the IDataErrorInfo Interface
    {
        get { return OnValidate(propertyName); }
    }

    /// <summary>
    /// Validates current instance properties using Data Annotations.
    /// </summary>
    /// <param name="propertyName"></param>
    /// <returns></returns>
    protected virtual string OnValidate(string propertyName)
    {
        if (string.IsNullOrEmpty(propertyName))
            throw new ArgumentException("Invalid property name", propertyName);

        string error = string.Empty;
        var value = this.GetType().GetProperty(propertyName).GetValue(this, null);
        var results = new List<ValidationResult>(1);

        var context = new ValidationContext(this, null, null) { MemberName = propertyName };

        var result = Validator.TryValidateProperty(value, context, results);

        if (!result)
        {
            var validationResult = results.First();
            error = validationResult.ErrorMessage;
        }

        return error;
    }
}

感谢Rachel在这里提示 以及非常开明的this link

相关问题