0

I've the follwing enum:

public enum eFlexCreateMode
{
    Man = 0,
    Auto = 1
}

which I convert into a dictionary in order to use inside my wpf page (binded as combobox)

Dictionary<int, string> EnumCreateMode = Enum.GetValues(typeof(eFlexCreateMode)).Cast<eFlexCreateMode>().ToDictionary(t => (int)t, t => t.ToString());

<ComboBox Grid.Column="10" Width="70" ItemsSource="{Binding Path=EnumCreateMode, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:ViewerFlexConfig}}" SelectionChanged="Combo_SelectionChanged" DisplayMemberPath="Value" SelectedValuePath="Value" SelectedValue="{Binding ConfigObject.Create_Mode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

Now I put the summary tag of each items of my enum and I would use it as tooltip for my combobox. Is it possible to achieve a task like this? There's no doc available

  • 1
    No, Use the `DescriptionAttribute`. You can get the content of it via reflection. – Trae Moore Dec 12 '19 at 14:36
  • (i'm assuming that you are writing about `` documentation comment) yes, generate xml documentation, load it , find enum, find enum element, read summary ... yeah, lots of work ... so as Trea wrote: use DescriptionAttribute – Selvin Dec 12 '19 at 14:38
  • If you want your UI to work with *any enum*, then attributes are the way to go. Otherwise manually create `Dictionary` in view model (initialized getter-only property), bind combobox `ItemsSource` to it, done. – Sinatr Dec 12 '19 at 14:45

1 Answers1

0

Here is a brief example of getting the Description value. You should add appropriate null checks and such... this is just an example.

// Usage Example
static void Main()
{
    var chanelDesc = Channel.Wholesale.GetEnumDescriptionValue();
    Console.WriteLine(chanelDesc);
    Console.ReadKey();
}

public static class EnumExtensions
{
    public static string GetEnumDescriptionValue<T>(this T @enum) where T : struct
    {
        if(!typeof(T).IsEnum)
            throw new InvalidOperationException();

        return typeof(T).GetField(@enum.ToString()).GetCustomAttribute<DescriptionAttribute>(false).Description;
    }
}

public enum Channel
{
    [Description("Banked - Retail")]
    Dtc,
    Correspondent,
    [Description("Banked - Wholesale")]
    Wholesale
}
Trae Moore
  • 1,759
  • 3
  • 17
  • 32
  • well, it's not good for binding ... Sintar provided the link to solution where `DescriptionAttribute` is used with custom Converter – Selvin Dec 12 '19 at 14:48
  • @Selvin, You're using MVVM as a design pattern, correct? This is a utility that will get the attribute value to set the property you should bind to... – Trae Moore Dec 12 '19 at 14:49