Click here to Skip to main content
15,890,670 members
Articles / Programming Languages / C#

Bit Flags Type Converter

Rate me:
Please Sign up or sign in to vote.
4.61/5 (14 votes)
20 Jun 2006CPOL3 min read 65.3K   393   35   10
An implementation of TypeConverter which allows you to edit bit flag enumerations in the PropertyGrid.

Sample Image

Introduction

I am a component developer at 10Tec Company. While developing one of our components, iGrid.NET, I came across a problem: the PropertyGrid control does not provide you with a comfortable-enough editor for enumerations marked with the Flags attribute (enumerations that can be treated as bit fields; that are a set of flags). The PropertyGrid treats them as usual enumerations, and allows you to select a single field from the drop-down list or enter a value as text. So, I decided to implement our own TypeConverter which would help to edit bit field properties.

There can be a few solutions to this problem, for example, we could show a check list box in the drop-down list. My solution is to show flags as sub-properties.

Using the code

To assign a custom type converter to a property, you should use the TypeConverterAttribute attribute:

C#
public class TestClass
{
  …
  [TypeConverter(typeof(FlagsEnumConverter))]
  public FontStyle FontStyle
  {
    get
    {
      …
    }
    set
    {
      …
    }
  }
  …
}

The parameter passed to the TypeConverterAttribute attribute should be inherited from the TypeConverter class or one of its descendents.

Our type converter is named FlagsEnumConverter, and is inherited from the standard .NET EnumConverter class:

C#
internal class FlagsEnumConverter: EnumConverter
{
  public override PropertyDescriptorCollection 
         GetProperties(ITypeDescriptorContext context, 
         object value, Attribute[] attributes)
  {
    …
  }
  public override bool GetPropertiesSupported(ITypeDescriptorContext context)
  {
    …
  }
}

The TypeConverter has several overridable properties and methods which allow you to customize the appearance of a property in the PropertyGrid. In our type converter, I overrode two methods: GetPropertiesSupported and GetProperties. By using these methods, we inform the PropertyGrid that our property is complex (has several nested properties), and return descriptors of these nested properties (we show a single nested boolean property for each bit flag):

C#
public override PropertyDescriptorCollection 
       GetProperties(ITypeDescriptorContext context, 
       object value, Attribute[] attributes)
{
  Type myType = value.GetType();
  string[] myNames = Enum.GetNames(myType);
  Array myValues = Enum.GetValues(myType);
  if(myNames != null)
  {
    PropertyDescriptorCollection myCollection = 
           new PropertyDescriptorCollection(null);
    for(int i = 0; i < myNames.Length; i++)
        myCollection.Add(new EnumFieldDescriptor(myType, 
                         myNames[i], context));
    return myCollection;
  }
}

Each bit flag (nested property) is represented with the EnumFieldDescriptor class inherited from the standard .NET class named SimplePropertyDescriptor. This is a base class which allows you to represent a custom property in the PropertyGrid. The main interests of the EnumFieldDescriptor class are the GetValue and SetValue methods. The GetValue method is called each time the PropertyGrid displays a custom property (a bit flag), and returns the value of the custom property (in our case it is a boolean value which indicates whether the bit flag is included in the enumeration property value):

C#
public override object GetValue(object component)
{
  return ((int)component & (int)Enum.Parse(ComponentType, Name)) != 0;
}

In the code snippet above, ComponentType is the type of the enumeration, and Name is the name of the enumeration field (bit flag).

The SetValue method is more complicated, it is called when the user modifies a custom property. In our case, it sets a particular bit flag to the enumeration value:

C#
public override void SetValue(object component, object value)
{
  bool myValue = (bool)value;
  int myNewValue;
  if(myValue)
    myNewValue = ((int)component) | (int)Enum.Parse(ComponentType, Name);
  else
    myNewValue = ((int)component) & ~(int)Enum.Parse(ComponentType, Name);

  FieldInfo myField = component.GetType().GetField("value__", 
                      BindingFlags.Instance | BindingFlags.Public);
  myField.SetValue(component, myNewValue);
  fContext.PropertyDescriptor.SetValue(fContext.Instance, component);
}

In this method, we accept a boxed enumeration value (the object type component parameter) which we should modify. The main problem is that an enumeration is a value type (non-reference type) and if we unbox it (convert from the object type to an enumeration type), we will obtain a different object, not the one passed with the component parameter. To solve it, I have done a little trick. An enumeration, in its core, stores its actual value in a private parameter named value__ (you can trace it with a disassembler or decompiler). I have accessed this parameter by using reflection, and set its value without unboxing.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWhy is it necessary to set the value of "value__" using reflection? Pin
Mizan Rahman15-May-12 1:00
Mizan Rahman15-May-12 1:00 
AnswerRe: Why is it necessary to set the value of "value__" using reflection? Pin
Sergey Gorbenko21-May-12 15:51
Sergey Gorbenko21-May-12 15:51 
GeneralDoesn't work Pin
Tim McCurdy6-Jul-07 7:32
Tim McCurdy6-Jul-07 7:32 
GeneralRe: Doesn't work Pin
Sergey Gorbenko30-Jul-07 20:53
Sergey Gorbenko30-Jul-07 20:53 
GeneralRe: Doesn't work Pin
Tim McCurdy31-Jul-07 16:26
Tim McCurdy31-Jul-07 16:26 
GeneralUPDATE Pin
SeriousM22-Dec-06 13:55
SeriousM22-Dec-06 13:55 
Hi!

I allow me to update the source because there was no check for Enums with NO [Flags] Attribut.
In this case, the enum will shown up as normal:

(Added fEnumHasFlags and a "return base.GetStandardValuesSupported" at
"public override bool GetStandardValuesSupported"
(BTW: sry for the long post and ty for this very nice tool!)

<code>
using System;
using System.ComponentModel;
using System.Reflection;
using System.Windows.Forms;

namespace FlagsEnumTypeConverter {
/// <summary>
/// Flags enumeration type converter.
/// </summary>
/// <remarks>
/// Using: [TypeConverter(typeof(FlagsEnumConverter))] über dem Attribute.
/// Wenn das Enum kein [Flags] Attribute hat, wird es ganz normal dargestellt
/// </remarks>
internal class FlagsEnumConverter : EnumConverter {
#region Nested Class EnumFieldDescriptor
/// <summary>
/// This class represents an enumeration field in the property grid.
/// </summary>
protected class EnumFieldDescriptor : SimplePropertyDescriptor {
#region Fields
/// <summary>
/// Stores the context which the enumeration field descriptor was created in.
/// </summary>
ITypeDescriptorContext fContext;
#endregion

#region Properties
public override AttributeCollection Attributes {
get {
return new AttributeCollection(new Attribute[] { RefreshPropertiesAttribute.Repaint });
}
}
#endregion

#region Constructor
/// <summary>
/// Creates an instance of the enumeration field descriptor class.
/// </summary>
/// <param name="componentType">The type of the enumeration.</param>
/// <param name="name">The name of the enumeration field.</param>
/// <param name="context">The current context.</param>
public EnumFieldDescriptor(Type componentType, string name, ITypeDescriptorContext context)
: base(componentType, name, typeof(bool)) {
fContext = context;
}
#endregion

#region Methods
/// <summary>
/// Retrieves the value of the enumeration field.
/// </summary>
/// <param name="component">
/// The instance of the enumeration type which to retrieve the field value for.
/// </param>
/// <returns>
/// True if the enumeration field is included to the enumeration;
/// otherwise, False.
/// </returns>
public override object GetValue(object component) {
return ((int)component & (int)Enum.Parse(ComponentType, Name)) != 0;
}

/// <summary>
/// Sets the value of the enumeration field.
/// </summary>
/// <param name="component">
/// The instance of the enumeration type which to set the field value to.
/// </param>
/// <param name="value">
/// True if the enumeration field should included to the enumeration;
/// otherwise, False.
/// </param>
public override void SetValue(object component, object value) {
bool myValue = (bool)value;
int myNewValue;
if (myValue)
myNewValue = ((int)component) | (int)Enum.Parse(ComponentType, Name);
else
myNewValue = ((int)component) & ~(int)Enum.Parse(ComponentType, Name);

FieldInfo myField = component.GetType().GetField("value__", BindingFlags.Instance | BindingFlags.Public);
myField.SetValue(component, myNewValue);
fContext.PropertyDescriptor.SetValue(fContext.Instance, component);
}

/// <summary>
/// Retrieves a value indicating whether the enumeration
/// field is set to a non-default value.
/// </summary>
public override bool ShouldSerializeValue(object component) {
return (bool)GetValue(component) != GetDefaultValue();
}

/// <summary>
/// Resets the enumeration field to its default value.
/// </summary>
public override void ResetValue(object component) {
SetValue(component, GetDefaultValue());
}

/// <summary>
/// Retrieves a value indicating whether the enumeration
/// field can be reset to the default value.
/// </summary>
public override bool CanResetValue(object component) {
return ShouldSerializeValue(component);
}

/// <summary>
/// Retrieves the enumerations field’s default value.
/// </summary>
private bool GetDefaultValue() {
object myDefaultValue = null;
string myPropertyName = fContext.PropertyDescriptor.Name;
Type myComponentType = fContext.PropertyDescriptor.ComponentType;

// Get DefaultValueAttribute
DefaultValueAttribute myDefaultValueAttribute = (DefaultValueAttribute)Attribute.GetCustomAttribute(
myComponentType.GetProperty(myPropertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic),
typeof(DefaultValueAttribute));
if (myDefaultValueAttribute != null)
myDefaultValue = myDefaultValueAttribute.Value;

if (myDefaultValue != null)
return ((int)myDefaultValue & (int)Enum.Parse(ComponentType, Name)) != 0;
return false;
}
#endregion
}
#endregion

#region Members
private bool fEnumHasFlags = true;
#endregion

#region Constructor
/// <summary>
/// Creates an instance of the FlagsEnumConverter class.
/// </summary>
/// <param name="type">The type of the enumeration.</param>
public FlagsEnumConverter(Type type)
: base(type) {
if (!type.IsEnum || type.GetCustomAttributes(typeof(FlagsAttribute), true).Length == 0) {
fEnumHasFlags = false;
}
}
#endregion

#region Methods
/// <summary>
/// Retrieves the property descriptors for the enumeration fields.
/// These property descriptors will be used by the property grid
/// to show separate enumeration fields.
/// </summary>
/// <param name="context">The current context.</param>
/// <param name="value">A value of an enumeration type.</param>
/// <param name="attributes"></param>
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) {
if (fEnumHasFlags) {
if (context != null) {
Type myType = value.GetType();
string[] myNames = Enum.GetNames(myType);
Array myValues = Enum.GetValues(myType);
if (myNames != null) {
PropertyDescriptorCollection myCollection = new PropertyDescriptorCollection(null);
for (int i = 0; i < myNames.Length; i++) {
if ((int)myValues.GetValue(i) != 0 &&
myNames[i].ToLower() != "all" &&
myNames[i].ToLower() != "alle" &&
myNames[i].ToLower() != "alles")

myCollection.Add(new EnumFieldDescriptor(myType, myNames[i], context));
}
return myCollection;
}
}
}
return base.GetProperties(context, value, attributes);
}

public override bool GetPropertiesSupported(ITypeDescriptorContext context) {
if (fEnumHasFlags) {
if (context != null) {
return true;
}
}
return base.GetPropertiesSupported(context);
}

public override bool GetStandardValuesSupported(ITypeDescriptorContext context) {
if (fEnumHasFlags) {
return false;
}
return base.GetStandardValuesSupported(context);
}
#endregion
}
}
</code>
GeneralRe: UPDATE Pin
greenxiar10-Aug-07 19:20
greenxiar10-Aug-07 19:20 
GeneralVB.NET Pin
Eric P Schneider23-Oct-06 15:21
Eric P Schneider23-Oct-06 15:21 
GeneralNice Pin
leppie20-Jun-06 10:26
leppie20-Jun-06 10:26 
GeneralExcellent! Pin
Alexey A. Popov20-Jun-06 8:23
Alexey A. Popov20-Jun-06 8:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.