我完全支持史蒂夫·摩根先生
因此,如果您的 ViewModel 并不总是需要某些属性,Required
那么您不应该将其装饰为必需的。
我不知道你为什么想要这个问题,但我想在某些情况下你需要PropertyOne
如果Required
有价值PropertyTwo
。
在这种情况下,您可能需要CustomValidationAttribute
检查这两个属性。
我正在使用这样的东西:
[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(...)
除了从属性中获取值来比较它,什么都不做。
希望这有帮助:)