HOW TO:在設計模式中執行控制項的自訂初始設定

您可以使用自訂設計工具,在設計環境建立元件和控制項時,將它們初始化。

範例

下列程式碼範例將示範如何在設計環境建立控制項時,將其初始化。 當您將控制項的執行個體拖曳至表單上時,就會產生建立作業,也會在您啟動表單的設計工具時,產生建立作業。 如需這個程式碼範例的完整說明,請參閱 HOW TO:在設計模式中擴充控制項的外觀和行為

' 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 Form 專案,而且該專案使用這個元件,您可能需要重新整理專案才能看到變更。 您通常必須先關閉包含元件的設計視窗,然後再重新開啟一次。

注意事項注意事項

您必須加入對設計階段組件 (System.Design.dll) 的參考。 這個組件未包含在 .NET Framework 4 Client Profile 中。 若要加入對 System.Design.dll 的參考,您必須將專案的目標 Framework 變更為 [.NET Framework 4]。

請參閱

工作

HOW TO:在設計模式中擴充控制項的外觀和行為

其他資源

自訂設計工具