Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

后端 未结 21 1435
终归单人心
终归单人心 2020-11-29 22:53

Does any one know how I can specify the Default value for a DateTime property using the System.ComponentModel DefaultValue Attribute?

for example I try this:

21条回答
  •  猫巷女王i
    2020-11-29 23:22

    I also wanted this and came up with this solution (I'm only using the date part - a default time makes no sense as a PropertyGrid default):

    public class DefaultDateAttribute : DefaultValueAttribute {
      public DefaultDateAttribute(short yearoffset)
        : base(DateTime.Now.AddYears(yearoffset).Date) {
      }
    }
    

    This just creates a new attribute that you can add to your DateTime property. E.g. if it defaults to DateTime.Now.Date:

    [DefaultDate(0)]
    

提交回复
热议问题