我想使用DisplayFormat数据注释来格式化我的模型数据,但我想使用存储在资源文件中的格式字符串.我已经能够将资源类型和名称传递给某些数据注释,例如指定错误消息时.如何告诉DisplayFormat从我的一个资源文件中获取格式字符串?
标准DisplayFormat属性不允许您这样做.您可以编写自定义属性来实现此功能:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class LocalizedDisplayFormatAttribute : Attribute, IMetadataAware
{
public string DataFormatStringResourceName { get; set; }
public bool ApplyFormatInEditMode { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
if (!string.IsNullOrEmpty(DataFormatStringResourceName))
{
if (ApplyFormatInEditMode)
{
metadata.EditFormatString = MyMessages.ResourceManager.GetString(DataFormatStringResourceName);
}
metadata.DisplayFormatString = MyMessages.ResourceManager.GetString(DataFormatStringResourceName);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
public class MyViewModel
{
[LocalizedDisplayFormat(DataFormatStringResourceName = "DobFormat", ApplyFormatInEditMode = true)]
public DateTime Dob { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在里面MyResources.resx你可以有一个DobFormat字符串值:{0:dd-MM-yyyy}.
| 归档时间: |
|
| 查看次数: |
1879 次 |
| 最近记录: |