Associating TypeConverter directly with an enumeration

I have the following scenario: I have an enumeration and you want to link it to show it in a DataGridView (Data Binding) in a DataGridViewTextBoxColumn.

Here is my listing:

//[TypeConverter(typeof(EnumStringConverter))]
   public enum YesNoNA
   {
      [EnumDescription("Yes")]
      Yes,
      [EnumDescription("No")]
      No,
      [EnumDescription("N/A")]
      NA
   }

And here is a simple property that uses it:

  [TypeConverter(typeof(EnumStringConverter))]
  public YesNoNA HighLimitWithinBounds { get; protected set; }

In the situation that I have above, typeconverter works just fine. It makes a translation for me.

However, this is more complicated than my ideal solution. If I put typeconverter on Enum (uncommented the above code) and commented out typeconverter in the property, typeconverter is no longer called!

I made this convention for other classes and it works great.

Why putting typeconverter directly on an enumeration doesn't work?

For reference, here is my typeconverter:

  public class EnumStringConverter : TypeConverter
   {
      public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, Object value, Type destinationType)
      {
         if (value != null && destinationType == typeof(string))
         {
            return "Edited to protect the innocent!";
         }
         return TypeDescriptor.GetConverter(typeof(Enum)).ConvertTo(context, culture, value, destinationType);
      }
      public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
      {
         if (destinationType == typeof(string))
         {
            return true;
         }
         return base.CanConvertTo(context, destinationType);
      }
   };
+5
1

, " , ". , , . , , . , .

1)

; , , , .

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Resources;

namespace AppResourceLib.Public.Reflection
{
  internal static class ResourceManagerCache
  {
    private static Dictionary<Type, ResourceManager> _resourceManagerMap =
      new Dictionary<Type, ResourceManager>();

    public static ResourceManager GetResourceManager(Type resourceType)
    {
      ResourceManager resourceManager = null;

      // Make sure the type is valid.
      if (null != resourceType)
      {
        // Try getting the cached resource manager.
        if (!ResourceManagerCache._resourceManagerMap.TryGetValue(resourceType, out resourceManager))
        {
          // If it is not in the cache create it.
          resourceManager = resourceType.InvokeMember(
            "ResourceManager",
            (BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic),
            null,                                                   
            null,                                                   
            null) as ResourceManager;

          // If it was created, add the resource manager to the cache.
          if (null != resourceManager)
          {
            ResourceManagerCache._resourceManagerMap.Add(resourceType, resourceManager);
          }
        }
      }

      return resourceManager;
    }
  }
}

2)

, Enum. , , enum.

using System;
using System.ComponentModel;

namespace AppResourceLib.Public.Reflection
{
  /// <summary>
  /// A resource type attribute that can be applied to enumerations.
  /// </summary>
  [AttributeUsage(AttributeTargets.Enum)]
  public sealed class LocalizedDescriptionAttribute : Attribute
  {
    /// <summary>
    /// The type of resource associated with the enum type.
    /// </summary>
    private Type _resourceType;

    public LocalizedDescriptionAttribute(Type resourceType)
    {
      this._resourceType = resourceType;
    }

    /// <summary>
    /// The type of resource associated with the enum type.
    /// </summary>
    public Type ResourceType
    {
      get
      {
        return this._resourceType;
      }
    }
  }
}

3)

, (.resx).

using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Windows.Data;

namespace AppResourceLib.Public.Reflection
{
  [ValueConversion(typeof(Object), typeof(String))]
  public class LocalizedDescriptionConverter : IValueConverter
  {
    public Object Convert(Object value, Type targetType, Object param, CultureInfo cultureInfo)
    {
      String description = null;

      if (null != value)
      {
        // If everything fails then at least return the value.ToString().
        description = value.ToString();

        // Get the LocalizedDescriptionAttribute of the object.
        LocalizedDescriptionAttribute attribute =
          value.GetType().GetCustomAttribute(typeof(LocalizedDescriptionAttribute))
          as LocalizedDescriptionAttribute;

        // Make sure we found a LocalizedDescriptionAttribute.
        if (null != attribute)
        {          
          ResourceManager resourceManager = 
            ResourceManagerCache.GetResourceManager(attribute.ResourceType);

          if (null != resourceManager)
          {
            // Use the ResourceManager to get the description you gave the object value.
            // Here we just use the object value.ToString() (the name of the object) to get
            // the string in the .resx file. The only constraint here is that you have to
            // name your object description strings in the .resx file the same as your objects.
            // The benefit is that you only have to declare the LocalizedDescriptionAttribute
            // above the object type, not an attribute over every object.
            // And this way is localizable.
            description = resourceManager.GetString(value.ToString(), cultureInfo);

            String formatString = (param as String);

            // If a format string was passed in as a parameter,
            // make a string out of that.
            if (!String.IsNullOrEmpty(formatString))
            {
              formatString = formatString.Replace("\\t", "\t");
              formatString = formatString.Replace("\\n", "\n");
              formatString = formatString.Replace("\\r", "\r");

              description = String.Format(formatString, value.ToString(), description);              
            }          
          }
        }
      }

      return description;      
    }

    public Object ConvertBack(Object value, Type targetType, Object param, CultureInfo cultureInfo)
    {
      throw new NotImplementedException();

      return null;
        }
  }
}

4) (.resx)

, , . , , "" , "" , .
, , .

public enum MyColors
{
  Black,
  Blue,
  White
}

:

|

|
|
|

5)

, , Enum LocalizedDescription. , LocalizedDescription, . , , , , , , .

using AppResourceLib.Public;
using AppResourceLib.Public.Reflection;

namespace MyEnums
{
  [LocalizedDescription(typeof(MyColorStrings))]
  public enum MyColors
  {
    Black,
    Blue,
    White
  }
}

, , "" . , . , ? ...

xaml , ( ComboBox ...). enum. , ...

      <!-- Enum Colors -->
  <ObjectDataProvider x:Key="MyColorEnums"
                      MethodName="GetValues"
                      ObjectType="{x:Type sys:Enum}">
    <ObjectDataProvider.MethodParameters>
      <x:Type TypeName="MyColors"/>
    </ObjectDataProvider.MethodParameters>
  </ObjectDataProvider>


  <!-- Enum Type Converter -->
  <LocalizedDescriptionConverter x:Key="EnumConverter"/>


  <!-- Dropdown Expand ComboBox Template -->
  <DataTemplate x:Key="MyColorsComboBoxTemplate">
    <Label Content="{Binding Path=., Mode=OneWay,
      Converter={StaticResource EnumConverter}}"
           Height="Auto" Margin="0" VerticalAlignment="Center"/>
  </DataTemplate>

  <!-- And finally the ComboBox that will display all of your enum values
    but will use the strings from the resource file instead of enum.ToString() -->
  <ComboBox Width="80" HorizontalAlignment="Left"
  ItemTemplate="{StaticResource MyColorsComboBoxTemplate}"
  ItemsSource="{Binding Source={StaticResource MyColorEnums}}">

, , . , , . , !

+2
source

All Articles