Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi experts,

let's assume an enumeration in a class
C#
public enum ImportantValues
{
    FirstValue,
    [System.ComponentModel.Browsable(false)]
    SecondValue,
    ThirdValue
}
Pay Regard to the Attribute Browsable, that should hide one enumeration value from the user when a Property of type ImportantValues is displayed in a PropertyGrid.

The values must be translated to different languages in PropertyGrid. Therefore I used a custom TypeConverter and overrode ConvertTo() and ConvertFrom().
The same TypeConverter overrides GetStandardValues() to display all the values in a drop down list.

I use Enum.GetValues() to get the list of values from the enumeration. But that doesn't obey the Browsable attribute.


Without a custom type converter at all, values are in the drop down, correctly hiding the one with the Browsalbe(false) attribute. But the values don't get translated.

With my custom type converter but without overriding GetStandardValues(), no values at all are in the drop down.

With my current implementation of GetStandardValues(), even the non-browsable values are displayed.


How does the standard type converter get the list of values to display in the drop down list in PropertyGrid? Can I use that too?
Posted

1 solution

Found it myself with the help of google[^] and this result[^].

C#
// Check for BrowsableAttribute on each enumeration value.
{
    System.Reflection.FieldInfo[] fields =
        context.PropertyDescriptor.PropertyType.GetFields(
            System.Reflection.BindingFlags.Public
            | System.Reflection.BindingFlags.Static
        );
    values = new List<object>(fields.Length);
    foreach (System.Reflection.FieldInfo field in fields)
    {
        BrowsableAttribute[] browsableAttributes = field.GetCustomAttributes(
            typeof(BrowsableAttribute),
            false
        ) as BrowsableAttribute[];
        if (
            browsableAttributes.Length <= 0
            || browsableAttributes[0].Browsable
        )
        // Add those values that are decorated with Browsable(true)
        //   or not decorated at all, which is by definition
        //   regarded as browsable.
        {
            values.Add(field.GetValue(context.Instance));
        }
    }
}
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900