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

Jag*_*san 7 .net c# user-controls windows-forms-designer winforms

我创建了一个自定义控件和组件,如下代码所示,

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

之后,我将控件添加到表单中,并将组件添加到表单中。然后尝试分配 Component.Control 值。分配值后,如果我尝试更改组件的样式属性,控件中的样式属性在设计器级别不会更改,如下图所示,

控件中的样式未更新

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

在此输入图像描述

Rez*_*aei 7

您需要更正代码中的一些内容。Style您的属性应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;
    }
}
Run Code Online (Sandbox Code Playgroud)

您应该检查是否Control不是,获取或设置Style控件的值。当属性值属于另一个控件时,您不需要定义成员变量来存储属性值。

另外,由于您不需要序列化组件的属性(因为它已为您的控件序列化),所以用DesignerSerializationVisibility具有值的属性来装饰它Hidden

此外,当您在编辑组件的属性时想要刷新PropertyGrid以显示其他属性(如Control.Style属性)的更改时,请使用具有值的属性来装饰它。StyleRefreshPropertiesRefreshProperties.All

  • 不客气。该行为不限于枚举。如果属性编辑器是像“字体”这样的模式对话框,或者像枚举这样的下拉菜单,则行为是相同的,并且在编辑属性值后,属性网格将刷新。使用“UITypeEditor”和“Modal”或“DropDown”作为编辑样式具有相同的行为。 (2认同)