Getting And Setting Property Attribute Value By Property Name

You can change property attribute value of an existing attribute at runtime. Below I created a helper class for getting and setting BrowsableAttribute value.

    public static class AttributeHelper
    {
        public static bool GetBrowsable(Type type, string propertyName)
        {
            PropertyDescriptor pd = TypeDescriptor.GetProperties(type)[propertyName];

            if (pd == null)
            {
                return false;
            }
            else
            {
                BrowsableAttribute ba = (BrowsableAttribute)pd.Attributes[typeof(BrowsableAttribute)];
                return (bool)ba.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(ba);
            }
        }

        public static void SetBrowsable(Type type, string propertyName, bool browsable)
        {
            PropertyDescriptor pd = TypeDescriptor.GetProperties(type)[propertyName];

            if (pd != null)
            {
                BrowsableAttribute ba = (BrowsableAttribute)pd.Attributes[typeof(BrowsableAttribute)];
                ba.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(ba, browsable);
            }
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *