【问题标题】:How to change Custom Control default size如何更改自定义控件默认大小
【发布时间】:2015-01-21 02:46:18
【问题描述】:

我是在 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

将控件添加到表单时有效,但是当我执行程序时,出现以下错误:“属性大小仅为只读”。当双击它时,它会导致Form Design中的以下代码:

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

这导致我将属性更改为读写,但是当我这样做时,控件大小再次保持在 150,50。

那么,我怎样才能将默认大小设置为特定的大小,并且在将控件添加到我的表单时不会遇到问题?

【问题讨论】:

    标签: .net vb.net winforms controls custom-controls


    【解决方案1】:

    试试这个

    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
    

    【讨论】:

      【解决方案2】:

      您是否尝试过设置最小和最大尺寸?

      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
      

      【讨论】:

        猜你喜欢
        • 2017-01-23
        • 1970-01-01
        • 2015-04-14
        • 1970-01-01
        • 2017-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多