设计师更改时,控件的属性未正确更新

时间:2017-03-01 12:50:20

标签: c# .net winforms user-controls windows-forms-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值。如果我尝试更改组件的样式属性,则在赋值后,控件中的样式属性不会在设计器级别更改,如下图所示,

Style not updated in control

如果我点击了控件的Style属性,它将更新,如下图所示,

enter image description here

1 个答案:

答案 0 :(得分:2)

您需要更正代码中的一些内容。 Style的{​​{1}}属性应更改为:

CustomComponent

您应该检查[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属性DesignerSerializationVisibility来装饰它。

另外,当您想要在编辑组件的Hidden属性时刷新PropertyGrid以显示其他属性(例如Control.Style属性)中的更改时,请使用{{1}进行装饰具有Style值的属性。

相关问题