如何使配置DisplayFormat属性 [英] How to make configurable DisplayFormat attribute

查看:291
本文介绍了如何使配置DisplayFormat属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期格式,如:

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?

推荐答案

这样做的问题是.NET只允许你把编译时常在属性中。另一种选择是从 DisplayFormatAttribute 继承和查找的显示格式在构造函数中,像这样:

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

这篇关于如何使配置DisplayFormat属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆