简体   繁体   中英

The design-time component property I add has a null reference error as an immutable value in design view

I'm trying to add a new property to a component at design time. The property is visible in design view, but the value can't be modified and displays as "Object reference not set to an instance of an object". If I need to instantiate the property, MSDN and google are failing me.

Where am I going wrong? Here is an abbreviated version of the code I'm using that demonstrates the problem.

[DesignerAttribute(typeof(designPropDesigner))]
public class designProp : Component
{
    public class designPropDesigner : ComponentDesigner
    {
        protected override void PreFilterProperties(IDictionary properties)
        {
            base.PreFilterProperties(properties);

            var prop = TypeDescriptor.CreateProperty(typeof(designPropDesigner), "prop", typeof(string), new Attribute[] { DesignOnlyAttribute.Yes, new DefaultValueAttribute("") });
            properties.Add("prop", prop);
        }
    }
}

The designer class needs to implement the property with appropriate get and set functions, and initialize should be overridden to include an initial value for the property, as demonstrated in the code below.

[DesignerAttribute(typeof(designPropDesigner))]
public class designProp : Component
{

    public class designPropDesigner : ComponentDesigner
    {
        private string _prop;

        public override void Initialize(IComponent component)
        {
            base.Initialize(component);

            this.prop = "value";
        }

        protected override void PreFilterProperties(IDictionary properties)
        {
            base.PreFilterProperties(properties);

            var prop = TypeDescriptor.CreateProperty(typeof(designPropDesigner), "prop", typeof(string), new Attribute[] { DesignOnlyAttribute.Yes, new DefaultValueAttribute("") });
            properties.Add("prop", prop);
        }

        private string prop
        {
            get
            {
                return _prop;
            }
            set
            {
                _prop = value;
            }
        }
    }
}

For additional info, check this MSDN article .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM