Edi Wang
Edi Wang

Reputation: 3637

How to make configurable DisplayFormat attribute

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?

Upvotes: 6

Views: 4955

Answers (2)

armen.shimoon
armen.shimoon

Reputation: 6401

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

Upvotes: 8

Mightymuke
Mightymuke

Reputation: 5144

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

Upvotes: 0

Related Questions