更改设计器时控件的 属性 未正确更新
Control's property not updated properly when change in designer
我创建了一个自定义控件和组件,如下面的代码,
public class CustomComponent : Component
{
private string style;
public CustomControl Control { get; set; }
public string Style
{
get
{
return style;
}
set
{
style = value;
Control.Style = value;
}
}
}
public class CustomControl : Control
{
string style;
public string Style
{
get
{
return style;
}
set
{
style = value;
}
}
}
之后,我将控件添加到窗体中,并将组件添加到窗体中。然后尝试分配 Component.Control 值。分配值后,如果我尝试更改组件的样式 属性,控件中的样式 属性 不会在设计器级别更改,如下图所示,
如果我点击了控件的样式 属性,它会像下图一样更新,
您需要更正代码中的几处内容。你的CustomComponent
的Style
属性应该改成这样:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[RefreshProperties(System.ComponentModel.RefreshProperties.All)]
public string Style
{
get
{
if (Control != null)
return Control.Style;
else
return null;
}
set
{
if (Control != null)
Control.Style = value;
}
}
你应该检查Control
是否不是,获取或设置控件的Style
值。当 属性 值属于另一个控件时,您不需要定义成员变量来存储它。
此外,由于您不需要为您的组件序列化 属性(因为它已为您的控件序列化),所以用具有 Hidden
的 DesignerSerializationVisibility
属性装饰它值。
另外当你想刷新 PropertyGrid
以显示其他 属性 的变化时(比如 Control.Style
属性) 当你编辑 Style
属性 的组件,用具有 RefreshProperties.All
值的 RefreshProperties
属性装饰它。
我创建了一个自定义控件和组件,如下面的代码,
public class CustomComponent : Component
{
private string style;
public CustomControl Control { get; set; }
public string Style
{
get
{
return style;
}
set
{
style = value;
Control.Style = value;
}
}
}
public class CustomControl : Control
{
string style;
public string Style
{
get
{
return style;
}
set
{
style = value;
}
}
}
之后,我将控件添加到窗体中,并将组件添加到窗体中。然后尝试分配 Component.Control 值。分配值后,如果我尝试更改组件的样式 属性,控件中的样式 属性 不会在设计器级别更改,如下图所示,
如果我点击了控件的样式 属性,它会像下图一样更新,
您需要更正代码中的几处内容。你的CustomComponent
的Style
属性应该改成这样:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[RefreshProperties(System.ComponentModel.RefreshProperties.All)]
public string Style
{
get
{
if (Control != null)
return Control.Style;
else
return null;
}
set
{
if (Control != null)
Control.Style = value;
}
}
你应该检查Control
是否不是,获取或设置控件的Style
值。当 属性 值属于另一个控件时,您不需要定义成员变量来存储它。
此外,由于您不需要为您的组件序列化 属性(因为它已为您的控件序列化),所以用具有 Hidden
的 DesignerSerializationVisibility
属性装饰它值。
另外当你想刷新 PropertyGrid
以显示其他 属性 的变化时(比如 Control.Style
属性) 当你编辑 Style
属性 的组件,用具有 RefreshProperties.All
值的 RefreshProperties
属性装饰它。