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

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

问题描述

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

所以我霍普一些可以启发我的

在这里我目前的测试code:

模型

 公共类Person //重新presents人的数据。
{
    ///<总结>
    ///获取或设置这个人的名字。
    ///< /总结>
    ///<&言论GT;
    ///空字符串或NULL是不允许的。
    ///允许的2以及多达40个大写和小写最低。
    ///< /言论>
    [需要]
    [RegularEx pression(@^ [A-ZA-Z'' - '\\ S] {2,40} $)]
    公共字符串名字{获得;组;}    ///<总结>
    ///获取或设置人的姓氏。
    ///< /总结>
    ///<&言论GT;
    ///空字符串或NULL是不允许的。
    ///< /言论>
    [需要]
    公共字符串名字{获得;组;}    公众诠释年龄{搞定;组;}
}

查看

 <窗​​口x:类=DataAnnotationstest.MainWindow
        的xmlns =htt​​p://schemas.microsoft.com/winfx/2006/xaml/$p$psentation
        的xmlns:X =htt​​p://schemas.microsoft.com/winfx/2006/xaml
        XMLNS:地方=CLR的命名空间:DataAnnotationstest
        标题=主窗口HEIGHT =350WIDTH =525>
    < Window.DataContext>
        <局部:人名字=Tomer的姓氏=Shamam/>
    < /Window.DataContext>
    <网格和GT;
        < StackPanel的保证金=4,4,51,4>
            <文本框的文本={绑定名字,ValidatesOnDataErrors = TRUE}/>
            <文本框的文本={结合姓氏,ValidatesOnDataErrors = TRUE}/>
            <文本框的文本={结合年龄,ValidatesOnDataErrors = TRUE}/>
        < / StackPanel的>
    < /网格和GT;
< /窗GT;

我需要实现人的东西?
我发现<一个href=\"http://stackoverflow.com/questions/7027613/how-to-retrieve-data-annotations-from-$c$c-programmatically\">here以下code,但就像我之前说,我不明白它是如何借机-.-

 公共静态牛逼GetAttributeFrom&LT; T&GT;(此对象实例,字符串propertyName的)其中T:属性
{
    VAR attrType = typeof运算(T);
    VAR财产= instance.GetType()的getProperty(propertyName的)。
    回报(T)财产.GetCustomAttributes(attrType,假)。首先();
}


解决方案

解决方案

 公共类人:IDataErrorInfo的//重新presents人的数据。
{
    ///&LT;总结&gt;
    ///获取或设置这个人的名字。
    ///&LT; /总结&gt;
    ///&LT;&言论GT;
    ///空字符串或NULL是不允许的。
    ///允许的2以及多达40个大写和小写最低。
    ///&LT; /言论&GT;
    [需要]
    [RegularEx pression(@^ [A-ZA-Z'' - '\\ S] {2,40} $)]
    公共字符串名字{获得;组;}    ///&LT;总结&gt;
    ///获取或设置人的姓氏。
    ///&LT; /总结&gt;
    ///&LT;&言论GT;
    ///空字符串或NULL是不允许的。
    ///&LT; /言论&GT;
    [需要]
    公共字符串名字{获得;组;}    公众诠释年龄{搞定;组;}    公共字符串错误//的IDataErrorInfo的接口的一部分
    {
        获得{抛出新NotImplementedException(); }
    } 串IDataErrorInfo.this [字符串参数propertyName] //部分的IDataErrorInfo的接口
    {
        {返回的OnValidate(propertyName的); }
    }    ///&LT;总结&gt;
    ///验证使用数据注释当前实例属性。
    ///&LT; /总结&gt;
    ///&LT; PARAM NAME =PROPERTYNAME&GT;&LT; /参数&GT;
    ///&LT;&回报GT;&LT; /回报&GT;
    受保护的虚拟字符串的OnValidate(字符串propertyName的)
    {
        如果(string.IsNullOrEmpty(propertyName的))
            抛出新的ArgumentException(无效的属性名称,propertyName的);        字符串错误=的String.Empty;
        VAR值= this.GetType()的getProperty(propertyName的).GetValue(这一点,空)。
        VAR的结果=新的List&LT;&为ValidationResult GT;(1);        VAR语境=新ValidationContext(本,NULL,NULL){MemberName = propertyName的};        VAR的结果= Validator.TryValidateProperty(价值的背景下,业绩);        如果(!结果)
        {
            变种的ValidationResult = results.First();
            错误= validationResult.ErrorMessage;
        }        返回错误;
    }
}

由于雷切尔在这里提示
此链接这是非常开明

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

here my current test code:

Model

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

View

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

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

解决方案

the solution

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

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

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

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