Partilhar via


How to: Perform Custom Initialization for Controls in Design Mode

You can use your custom designer to initialize components and controls as they are created by the design environment.

Example

The following code example demonstrates how to initialize a control when it is created by the design environment. This creation occurs when you drag an instance of the control onto your form, and it also occurs when you start the designer for your form. For a complete explanation of this code example, see How to: Extend the Appearance and Behavior of Controls in Design Mode.

' 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);
    }
}

When the design environment creates an instance of your control or component, it calls your designer's InitializeNewComponent method. In the previous code example, the control's BackColor property is set by using a PropertyDescriptor.

Compiling the Code

When you make changes to the design-time aspects of a component, you need to rebuild the control project. In addition, if there is another Windows Forms project that is currently open and uses this component, you will probably need to refresh the project to see the changes. Typically, you need to close and reopen the design window containing the component.

See Also

Tasks

How to: Extend the Appearance and Behavior of Controls in Design Mode

Other Resources

Custom Designers