MVVM - 对视图模型中的属性进行验证

时间:2012-12-17 21:18:59

标签: c# silverlight xaml mvvm

我正在尝试在视图模型中为我的属性进行自定义验证,尽管它似乎没有达到我在验证逻辑中的断点。我正在使用我之前做的另一个验证(我在我的模型中使用它并且它工作)尝试输入验证逻辑,以便我可以根据我的需要进行自定义

验证

    [Required]
    [CustomValidation(typeof(CardRangeValidator), "CrossValidateFirstWithLast")]

属性:

    public const string ExpiresOnPropertyName = "ExpiresOn";

    private DateTime? expiresOn = DateTime.Today.AddYears(1);

    /// <summary>
    /// Gets the ExpiresOn property.
    /// TODO Update documentation:
    /// Changes to that property's value raise the PropertyChanged event. 
    /// This property's value is broadcasted by the Messenger's default instance when it changes.
    /// </summary>
    public DateTime? ExpiresOn
    {
        get
        {
            return expiresOn;
        }

        set
        {
            if (expiresOn == value)
            {
                return;
            }

            expiresOn = value;

            RaisePropertyChanged(ExpiresOnPropertyName);
        }
    }

验证逻辑:

using System.ComponentModel.DataAnnotations;

namespace Fsc.Feenics.Clients.Silverlight2.Web.Models.Shared
{
public class CardRangeValidator
{
    public static ValidationResult CrossValidateFirstWithLast(int number,     ValidationContext context)
    {
        var cardRangeInfo = context.ObjectInstance as CardRangeInfo;
        if (cardRangeInfo == null) return ValidationResult.Success;
        return ValidateFirstLessThanLast(number, cardRangeInfo.Last);
    }

    public static ValidationResult CrossValidateLastWithFirst(int number, ValidationContext context)
    {
        var cardRangeInfo = context.ObjectInstance as CardRangeInfo;
        if (cardRangeInfo == null) return ValidationResult.Success;
        return ValidateFirstLessThanLast(cardRangeInfo.First, number);
    }

    private static ValidationResult ValidateFirstLessThanLast(int firstNumber, int lastNumber)
    {
        return firstNumber <= lastNumber ? ValidationResult.Success : new ValidationResult("First number in range must be less than or equal to last number in range", new string[] { "First", "Last" });
    }
}
}

0 个答案:

没有答案