我得到的日期格式如下:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? CreatedOn { get; set; }现在,我想让我的应用程序中的每个日期时间格式都从一个配置文件中读取。像这样:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = SomeClass.GetDateFormat())]
public DateTime? CreatedOn { get; set; }但这不会编译。
我该怎么做呢?
发布于 2012-11-27 10:51:01
这样做的问题是.NET只允许您将编译时常量放在属性中。另一种选择是继承DisplayFormatAttribute并在构造函数中查找显示格式,如下所示:
SomeClass.cs
public class SomeClass
{
public static string GetDateFormat()
{
// return date format here
}
}DynamicDisplayFormatAttribute.cs
public class DynamicDisplayFormatAttribute : DisplayFormatAttribute
{
public DynamicDisplayFormatAttribute()
{
DataFormatString = SomeClass.GetDateFormat();
}
}然后,您可以这样使用它:
[DynamicDisplayFormat(ApplyFormatInEditMode = true)]
public DateTime? CreatedOn { get; set; }发布于 2012-11-27 10:39:03
我在一个基类中创建了一个字符串常量,并将视图模型子类化,这样我就可以使用它了。
例如:
public class BaseViewModel : IViewModel
{
internal const string DateFormat = "dd MMM yyyy";
}
public class MyViewModel : BaseViewModel
{
[DisplayFormat(ApplyFormatInEditMode = true,
DataFormatString = "{0:" + DateFormat + "}")]
public DateTime? CreatedOn { get; set; }
}这样我也可以用子类化来引用它:
public class AnotherViewModel
{
[DisplayFormat(ApplyFormatInEditMode = true,
DataFormatString = "{0:" + BaseViewModel.DateFormat + "}")]
public DateTime? CreatedOn { get; set; }
}https://stackoverflow.com/questions/13576571
复制相似问题