【问题标题】:Adding Controls to a Container within a Structure Declaration in VB .NET在 VB .NET 的结构声明中向容器添加控件
【发布时间】:2012-02-15 03:34:26
【问题描述】:

有没有办法在 VB .NET 的结构声明中向容器中添加控件?

我真正想做的是:

Structure LabelContainer
    Dim pnlContainer As New Panel
    Dim lblTime As New Label
    Dim lblStudent As New Label
    Dim lblTeacher As New Label
    lblTime.Parent = pnlContainer
    lblStudent.Parent = pnlContainer
    lblTeacher.Parent = pnlContainer
End Structure

但这在 VB .NET 中不起作用。有没有实现同样的目标?

【问题讨论】:

  • 您不能将代码放入结构声明中。使用一个类,将代码放在构造函数中。并拿起一本关于 vb.net 编程的书。

标签: vb.net data-structures panel containers parent-child


【解决方案1】:

结构对控件所需事件的处理非常有限,例如在创建控件时触发的 InitializeComponent() 事件。有关详细信息,请参阅此内容:

http://www.codeproject.com/Articles/8607/Using-Structures-in-VB-NET

您可以做的是创建一个从面板继承的类,例如:

Public Class LabelContainer
    Inherits Panel
    Friend WithEvents lblTeacher As System.Windows.Forms.Label
    Friend WithEvents lblStudent As System.Windows.Forms.Label
    Friend WithEvents lblTime As System.Windows.Forms.Label

    Private Sub InitializeComponent()
        Me.lblTime = New System.Windows.Forms.Label()
        Me.lblStudent = New System.Windows.Forms.Label()
        Me.lblTeacher = New System.Windows.Forms.Label()
        Me.SuspendLayout()
        '
        'lblTime
        '
        Me.lblTime.AutoSize = True
        Me.lblTime.Location = New System.Drawing.Point(0, 0)
        Me.lblTime.Name = "lblTime"
        Me.lblTime.Size = New System.Drawing.Size(100, 23)
        Me.lblTime.TabIndex = 0
        Me.lblTime.Text = "Label1"
        '
        'lblStudent
        '
        Me.lblStudent.AutoSize = True
        Me.lblStudent.Location = New System.Drawing.Point(0, 0)
        Me.lblStudent.Name = "lblStudent"
        Me.lblStudent.Size = New System.Drawing.Size(100, 23)
        Me.lblStudent.TabIndex = 0
        Me.lblStudent.Text = "Label2"
        '
        'lblTeacher
        '
        Me.lblTeacher.AutoSize = True
        Me.lblTeacher.Location = New System.Drawing.Point(0, 0)
        Me.lblTeacher.Name = "lblTeacher"
        Me.lblTeacher.Size = New System.Drawing.Size(100, 23)
        Me.lblTeacher.TabIndex = 0
        Me.lblTeacher.Text = "Label3"
        Me.ResumeLayout(False)

    End Sub
End Class

【讨论】:

    【解决方案2】:

    你可以在你的 Struct 中添加一个 sub:

    Structure LabelContainer
        Dim pnlContainer As Panel
        Dim lblTime As Label
        Dim lblStudent As Label
        Dim lblTeacher As Label
        Sub AddControls()
            lblTime.Parent = pnlContainer
            lblStudent.Parent = pnlContainer
            lblTeacher.Parent = pnlContainer
        End Sub
    End Structure
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多