2014-11-23 120 views
0

我是在VB.NET中添加自定義控件的新手。 我想要一個具有默認大小和圖片的類似PictureBox的控件,兩者最好不可更改。
我開始通過添加一個新的類到我的項目,然後添加以下代碼:如何更改自定義控件的默認大小

Public Class CustomControl 
Inherits Windows.Forms.PictureBox 
    Protected Overrides Sub OnCreateControl() 
     MyBase.OnCreateControl() 
     Me.Image = Global.Mazerino.My.Resources.Resources.ControlImage   
     MyBase.Size = New System.Drawing.Size(20, 20) 'Also tried setting Width and Height 
                 'properties instead. 
    End Sub 
End Class 

我執行的項目,關閉,然後加控制;該圖像已添加,但尺寸未更改。默認控件的大小爲150,50

所以我代替添加以下代碼:

Private ControlSize As Size = New Size(10, 10) 
Overloads Property Size As Size   
    Get 
     Return ControlSize 
    End Get 

    Set(value As Size) 
    'Nothing here... 
    End Set 
End Property 

但它並不能工作,所以後來我想:

Shadows ReadOnly Property Size As Size 
    Get 
     Return ControlSize 
    End Get 
End Property 

哪些工作當將控件添加到窗體時,但是當我執行該程序時,出現以下錯誤:「屬性大小僅爲只讀」。當雙擊它,它會導致下面的代碼在窗體設計:

Me.CustomControl1.Size = New System.Drawing.Size(10, 10) 

這使我改變屬性來讀取和寫入,但我這樣做的時候,再一次,控制規模保持在150 50。

那麼,我怎樣才能設置一個默認大小到一個特定的,並沒有麻煩添加控制到我的表單?

回答

0

您是否嘗試設置最小和最大尺寸是多少?

Public Class CustomControl Inherits Windows.Forms.PictureBox 
    Protected Overrides Sub OnCreateControl() 
     MyBase.OnCreateControl() 
     MyBase.SizeMode = PictureBoxSizeMode.StretchImage 
     Me.Image = Global.Mazerino.My.Resources.Resources.ControlImage   
     MyBase.Size = New System.Drawing.Size(20, 20) 'Also tried setting Width and Height 
                 'properties instead. 
     MyBase.MaximumSize = New Size(20,20) 
     MyBase.MinimumSize = New Size(20,20) 
    End Sub 
End Class 
0

試試這個

Public Class CustomControl : Inherits Windows.Forms.PictureBox 

    Private ReadOnly INMUTABLE_SIZE As Size = New Size(20, 20) 

    Public Shadows Property Size As Size 
     Get 
      Return INMUTABLE_SIZE 
     End Get 
     Set(value As Size) 
      MyBase.Size = INMUTABLE_SIZE 
     End Set 
    End Property 

    Protected Overrides Sub OnSizeChanged(e As System.EventArgs) 
     MyBase.Size = INMUTABLE_SIZE 
     MyBase.OnSizeChanged(e) 
    End Sub 

End Class