简体   繁体   中英

Using Properties.Settings.Default as an argument for DisplayName

I am attempting to store values for a displayName attribute from a setting held 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 clearly is not. Is there any simple way to get around this?

Since the DisplayName property is virtual, you could do something like that:

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 that:

[DisplayNameSettingsKey("field2Name")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM