How to make configurable DisplayFormat attribute

只谈情不闲聊 提交于 2019-11-28 07:54:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!