Search code examples
c#.netwinformsattributessystem.componentmodel

CategoryAttribute returns "Misc" for category named as "Default"


I have a class named CommonKeys.cs and it contains a property as below,

public class Test
{
   private SolidBrush _backgroundbrush;
   [CategoryAttribute("Default")]
   public SolidBrush BackgroundBrush
   {
       get
       {
           return this._backgroundbrush;
       }
       set
       {
           this._backgroundbrush = value;
       }
   }
}

When i access the above property and its Category with below code, it return "Misc" as category instead of the original Category "Default".

public static void GetCategoryName()
{
   PropertyInfo[] Props = typeof(Test).GetProperties(BindingFlags.Public | BindingFlags.Instance);
   foreach (PropertyInfo prop in Props)
   {
       var attributes = prop.GetCustomAttributes(false);
       string categoryName = String.Empty;
       foreach (var attr in attributes)
       {
           if (attr is CategoryAttribute)
           {
               categoryName = (attr as CategoryAttribute).Category;
           }
       }
   }
}

But when i change the category name other than "Default", it return the exact category name.

My question is, why "Misc" is returned when "Default" is set as category.

Regards,

Amal Raj


Solution

  • It's because of implementation of the CategoryAttribute class. For some values it gets the category name from string resources of .net framework. On of those values is Default which is defined this way:

    PropertyCategoryDefault = Misc
    

    You will receive another text also for Config, DragDrop and WindowStyle:

    PropertyCategoryConfig = Configurations
    PropertyCategoryDragDrop = Drag Drop
    PropertyCategoryWindowStyle = Window Style
    

    Here is related implemenattions:

    public string Category {
        get {
            if (!localized) {
                localized = true;
                string localizedValue = GetLocalizedString(categoryValue);
                if (localizedValue != null) {
                    categoryValue = localizedValue;
                }
            }
            return categoryValue;
        }
    }
    protected virtual string GetLocalizedString(string value) {
    #if !SILVERLIGHT
        return (string)SR.GetObject("PropertyCategory" + value);
    #else
        bool usedFallback;
        string localizedString = SR.GetString("PropertyCategory" + value, out usedFallback);
        if (usedFallback) {
            return null;
        }
        return localizedString;
    #endif
    }