私は完全にスティーブ・モーガン氏と一緒です
したがって、ViewModelが常に何らかのプロパティを必要としない場合Required
は、それを必須として装飾するべきではありません。
なぜこの問題を望んでいるのかわかりませんが、場合によっては、価値がある場合はそうする必要があるとPropertyOne
思いRequired
ますPropertyTwo
。
この場合、CustomValidationAttribute
これら2つのプロパティを確認する必要がある場合があります。
私はこのようなものを使用しています:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class PropertyNeededAttribute : ValidationAttribute
{
private const string defaultErrorMessage = "'{0}' needs '{1}' to be valid.";
public PropertyNeededAttribute(string originalProperty, string neededProperty)
: base(defaultErrorMessage)
{
NeededProperty = neededProperty;
OriginalProperty = originalProperty;
}
public string NeededProperty { get; private set; }
public string OriginalProperty { get; private set; }
public override object TypeId
{
get { return new object(); }
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
OriginalProperty, NeededProperty);
}
public override bool IsValid(object value)
{
object neededValue = Statics.GetPropertyValue(value, NeededProperty);
object originalValue = Statics.GetPropertyValue(value, OriginalProperty);
if (originalValue != null && neededValue == null)
return false;
return true;
}
}
注:Statics.GetPropertyValue(...)
プロパティから値を取得して比較する以外に何もしません。
これがお役に立てば幸いです:)