简体   繁体   English

我添加的设计时组件属性在设计视图中具有为空值的空引用错误。

[英]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. 如果我需要实例化该属性,则MSDN和Google会让我失望。

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. 设计器类需要使用适当的get和set函数来实现该属性,并且应该重写initialize,以包括该属性的初始值,如下面的代码所示。

[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 . 有关其他信息,请查看此MSDN文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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