我正在尝试实现自己的RequiredAttribute,我在其中调用自定义资源处理程序:
public class LocalizedValidationAttributes
{
public class LocalizedRequiredAttribute : RequiredAttribute
{
private String _resourceString = String.Empty;
public new String ErrorMessage
{
get { return _resourceString; }
set { _resourceString = GetMessageFromResource(value); }
}
}
private static String GetMessageFromResource(String resourceTag)
{
return ResourceManager.Current.GetResourceString(resourceTag);
}
}
我用以下方式打电话:
[LocalizedValidationAttributes.LocalizedRequiredAttribute(ErrorMessage = "test")]
public String Text { get; set; }
但是从不调用ErrorMessage的getter。
任何提示?谢谢!
答案 0 :(得分:5)
试试这样:
public class LocalizedRequiredAttribute : RequiredAttribute
{
public override string FormatErrorMessage(string name)
{
return ResourceManager.Current.GetResourceString(name);
}
}
或者像这样:
public class LocalizedRequiredAttribute : RequiredAttribute
{
public LocalizedRequiredAttribute(string resourceTag)
{
ErrorMessage = GetMessageFromResource(resourceTag);
}
private static String GetMessageFromResource(String resourceTag)
{
return ResourceManager.Current.GetResourceString(resourceTag);
}
}
然后:
[LocalizedValidationAttributes.LocalizedRequiredAttribute("test")]
public String Text { get; set; }