C# 我添加的设计时组件属性在设计视图中作为不可变值存在空引用错误
我试图在设计时向组件添加一个新属性。该属性在设计视图中可见,但无法修改该值,并显示为“对象引用未设置为对象实例”。如果我需要实例化属性,MSDN和google会让我失望 我哪里做错了?下面是我正在使用的代码的缩写版本,它演示了这个问题C# 我添加的设计时组件属性在设计视图中作为不可变值存在空引用错误,c#,design-time,C#,Design Time,我试图在设计时向组件添加一个新属性。该属性在设计视图中可见,但无法修改该值,并显示为“对象引用未设置为对象实例”。如果我需要实例化属性,MSDN和google会让我失望 我哪里做错了?下面是我正在使用的代码的缩写版本,它演示了这个问题 [DesignerAttribute(typeof(designPropDesigner))] public class designProp : Component { public class designPropDesigner : Componen
[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;
}
}
}
}
有关更多信息,请查看