如何在 MVVM 中捕获 DataAnnotations 验证 [英] How to catch DataAnnotations Validation in MVVM

查看:36
本文介绍了如何在 MVVM 中捕获 DataAnnotations 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do i catch the validation from the DataAnnotations ? i research here but i didn't understand how it works

所以我希望你们中的一些人可以启发我的

so i hoppe some of you can enlighten my

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 实现一些其他的东西?我在这里找到了以下代码,但就像我之前说的不明白它是如何工作的 -.-

do i need to implement something else to Person? i found here the following code but like i said before i didn't understand how it's worke -.-

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

推荐答案

解决方案

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 的提示和这个链接,这是非常开明的

thanks to Rachel for here hint and to this link which was very enlightened

这篇关于如何在 MVVM 中捕获 DataAnnotations 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆