簡體   English   中英

我添加的設計時組件屬性在設計視圖中具有為空值的空引用錯誤。

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

我正在嘗試在設計時將新屬性添加到組件。 該屬性在設計視圖中可見,但是無法修改該值,並顯示為“對象引用未設置為對象的實例”。 如果我需要實例化該屬性,則MSDN和Google會讓我失望。

我要去哪里錯了? 這是我正在使用的代碼的縮寫版本,用於演示該問題。

[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);
        }
    }
}

設計器類需要使用適當的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;
            }
        }
    }
}

有關其他信息,請查看此MSDN文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM