2011-09-13 57 views
2

我想實現我自己的RequiredAttribute標籤,在其中我調用自定義的資源處理程序:派生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不會被調用。

任何提示?謝謝!

回答

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