如何:在设计模式下执行控件的自定义初始化

您可以使用自定义设计器来初始化组件和控件,因为它们是由设计环境创建的。

示例

下面的代码示例演示当设计环境创建一个控件时如何初始化该控件。 当您将控件的实例拖动到您的窗体上时,就会发生这种创建活动;当您为窗体启动设计器时,也会发生此创建。 有关此代码示例的完整解释,请参见 如何:在设计模式下扩展控件的外观和行为

' This demonstrates changing the appearance of a control while
' it is being designed. In this case, the BackColor property is
' set to LightBlue. 
Public Overrides Sub InitializeNewComponent( _
ByVal defaultValues As IDictionary)

    MyBase.InitializeNewComponent(defaultValues)

    Dim colorPropDesc As PropertyDescriptor = _
    TypeDescriptor.GetProperties(Component)("BackColor")

    If colorPropDesc IsNot Nothing AndAlso _
       colorPropDesc.PropertyType Is GetType(Color) AndAlso _
       Not colorPropDesc.IsReadOnly AndAlso _
       colorPropDesc.IsBrowsable Then
        colorPropDesc.SetValue(Component, Color.LightBlue)
    End If
End Sub
// This demonstrates changing the appearance of a control while
// it is being designed. In this case, the BackColor property is
// set to LightBlue. 

public override void InitializeNewComponent(IDictionary defaultValues)
{
    base.InitializeNewComponent(defaultValues);

    PropertyDescriptor colorPropDesc = 
        TypeDescriptor.GetProperties(Component)["BackColor"];

    if (colorPropDesc != null &&
        colorPropDesc.PropertyType == typeof(Color) &&
        !colorPropDesc.IsReadOnly &&
        colorPropDesc.IsBrowsable)
    {
        colorPropDesc.SetValue(Component, Color.LightBlue);
    }
}

当设计环境创建控件或组件的实例时,它会调用设计器的 InitializeNewComponent 方法。 在前面的代码示例中,控件的 BackColor 属性是通过使用 PropertyDescriptor 设置的。

编译代码

当您对组件的设计时方面做更改时,您需要重新生成控件项目。 此外,如果有另外一个 Windows 窗体项目当前处于打开状态并且正在使用此组件,您可能需要刷新该项目才能看到更改。 一般情况下,需要关闭并重新打开包含组件的设计窗口。

提示

必须添加对设计时程序集 System.Design.dll 的引用。 此程序集不包含在 .NET Framework 4 Client Profile 中。 若要添加对 System.Design.dll 的引用,必须将项目的目标框架更改为“.NET Framework 4”

请参见

任务

如何:在设计模式下扩展控件的外观和行为

其他资源

自定义设计器