2

I am able to apply my IValueConverter which converters my enum and shows the Display-name Attribute on the xaml side. I'm wondering how would I do the same in code-behind?

EnumToDisplayAttribConverter.cs

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    if (!value.GetType().IsEnum)
    {
        throw new ArgumentException("Value must be an Enumeration type");
    }

    var fieldInfo = value.GetType().GetField(value.ToString());
    var array = fieldInfo.GetCustomAttributes(false);

    foreach (var attrib in array)
    {
        if (attrib is DisplayAttribute)
        {
            DisplayAttribute displayAttrib = attrib as DisplayAttribute;

            //if there is no resource assume we don't care about lization
            if (displayAttrib.ResourceType == null)
                return displayAttrib.Name;

            // per http://stackoverflow.com/questions/5015830/get-the-value-of-displayname-attribute
            ResourceManager resourceManager = new ResourceManager(displayAttrib.ResourceType.FullName, displayAttrib.ResourceType.Assembly);
            var entry =
                    resourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true)
                      .OfType<DictionaryEntry>()
                      .FirstOrDefault(p => p.Key.ToString() == displayAttrib.Name);

            var key = entry.Value.ToString();
            return key;
        }
    }

        //if we get here than there was no attrib, just pretty up the output by spacing on case
        // per http://stackoverflow.com/questions/155303/net-how-can-you-split-a-caps-delimited-string-into-an-array
        string name = Enum.GetName(value.GetType(), value);
        return Regex.Replace(name, "([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))", "$1 ");
}\\

What I've Tried - Code Behind

var converter = new EnumToDisplayAttribConverter();
var converted =
        (IEnumerable<ReportArguements.NoteOptions>)
            converter.Convert(
                Enum.GetValues(typeof(ReportArguements.NoteOptions))
                    .Cast<ReportArguements.NoteOptions>(), typeof(IEnumerable<ReportArguements.NoteOptions>), null, null);

var notesOption = new ComboBox
{
    ItemsSource = converted,
    SelectedIndex = 0,
};

May I ask if I can get assistance on how to properly bind to an enum and converting the collection to use Display-Name attribute using code behind.

Working solution

var datatemplate = new DataTemplate();
Binding binding = new Binding();
binding.Converter = new EnumToDisplayAttribConverter();

FrameworkElementFactory textElement = new FrameworkElementFactory(typeof(TextBlock));
textElement.SetBinding(TextBlock.TextProperty, binding);
datatemplate.VisualTree = textElement;

var notesOption = new ComboBox
{
    SelectedIndex = 0,
};

notesOption.ItemTemplate = datatemplate;
notesOption.ItemsSource = Enum.GetValues(typeof(ReportArguements.NoteOptions)).Cast<ReportArguements.NoteOptions>();
return notesOption;
Master
  • 2,038
  • 2
  • 27
  • 77
  • 1
    Why not use a custom `ItemTemplate` on your `ComboBox`, and perform the conversion there? That allows you to select actual enum values, instead of having to convert back from their display names - and removes the need for any conversions in your code-behind. – Pieter Witvoet Dec 09 '15 at 16:28
  • @PieterWitvoet Thanks for the suggestion, definitely a plausible option because that's where I would normally put the converter, in the ItemTemplate. I'll read up on how to set ItemTemplate in code behind. – Master Dec 09 '15 at 16:57
  • Is there a particular reason for doing this in the code-behind then? – Pieter Witvoet Dec 09 '15 at 17:12
  • Hi @PieterWitvoet I've accomplished this in XAML, I wanted to give it a try in code behind. May I ask where am I going wrong for the ItemTemplate? I just attempted it but the converter is never fired. – Master Dec 09 '15 at 17:17
  • I don't have time to check right now, but maybe setting `notesOption.Style` (or just `notesOption.ItemTemplate` - the style shouldn't be necessary) explicitly will work? – Pieter Witvoet Dec 09 '15 at 17:22
  • @PieterWitvoet That worked! THANKS !!! – Master Dec 09 '15 at 17:25

0 Answers0