Using Properties.Settings.Default as an argument for DisplayName

I am trying to save the displayName attribute values ​​from a parameter stored in the app.config file.

[System.ComponentModel.DisplayName(Properties.Settings.Default.field2Name)]

This does not work, because it must be a constant value, which Properties.Settings.Default is not explicitly. Is there an easy way around this?

+1
source share
1 answer

Since the property DisplayNameis virtual, you can do something like this:

public class DisplayNameSettingsKeyAttribute : DisplayNameAttribute
{
    private readonly string _settingsKey;

    public DisplayNameSettingsKeyAttribute(string settingsKey)
    {
        _settingsKey = settingsKey;
    }

    public string SettingsKey
    {
        get { return _settingsKey; }
    }

    public override string DisplayName
    {
        get { return (string)Properties.Settings.Default[_settingsKey]; }
    }
}

And use it like this:

[DisplayNameSettingsKey("field2Name")]
+6
source

All Articles