如何更改自定义控件的默认大小
问题描述:
我是在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。
那么,我怎样才能设置一个默认大小到一个特定的,并没有麻烦添加控制到我的表单?
答
您是否尝试设置最小和最大尺寸是多少?
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
答
试试这个
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