问题
I got a date format like:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? CreatedOn { get; set; }
Now, I want to make every datetime format in my application read from one config file. like:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = SomeClass.GetDateFormat())]
public DateTime? CreatedOn { get; set; }
but this will not compile.
How can I do this?
回答1:
The problem with this is .NET only allows you to put compile-time constants in attributes. Another option is to inherit from DisplayFormatAttribute
and lookup the display format in the constructor, like so:
SomeClass.cs
public class SomeClass
{
public static string GetDateFormat()
{
// return date format here
}
}
DynamicDisplayFormatAttribute.cs
public class DynamicDisplayFormatAttribute : DisplayFormatAttribute
{
public DynamicDisplayFormatAttribute()
{
DataFormatString = SomeClass.GetDateFormat();
}
}
Then you can use it as so:
[DynamicDisplayFormat(ApplyFormatInEditMode = true)]
public DateTime? CreatedOn { get; set; }
回答2:
I created a string constant in a base class and subclassed my view models off that so I could use it.
For example:
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; }
}
This way I could also reference it with subclassing:
public class AnotherViewModel
{
[DisplayFormat(ApplyFormatInEditMode = true,
DataFormatString = "{0:" + BaseViewModel.DateFormat + "}")]
public DateTime? CreatedOn { get; set; }
}
来源:https://stackoverflow.com/questions/13576571/how-to-make-configurable-displayformat-attribute