访问动态创建的UserControl的公共声明-WinForms

时间:2019-04-11 13:06:20

标签: vb.net user-controls

逻辑

有一个Form1,其中的FlowLayoutPanel'flowItems'由UserControl'UCItem'填充。为了填充flowItem,使用了一个数组。 For-Loop在数组上循环并创建一个新的UCItem,为其指定标签名称和编号,并将其添加到flowItem。所有这部分都有效。

问题

每次单击新创建的UCItem时,我想更改公共声明的布尔变量'isChecked'。为此,我添加了一个事件处理程序(UCItem.Click),该事件处理程序获取并设置了属性。

但是,我无法访问UCItem中的公共布尔变量。

代码:UC_Item.vb

Public isChecked As Boolean = False

Private Sub toggle_color()
    If Me.BackColor = Color.FromArgb(24, 24, 24) Then
        Me.BackColor = Color.RoyalBlue
        Me.txtName.BackColor = Color.RoyalBlue
        Me.txtName.ForeColor = Color.Black
        Me.BackgroundImage = Nothing
        isChecked = True
    Else
        Me.BackColor = Color.FromArgb(24, 24, 24)
        Me.txtName.BackColor = Color.Black
        Me.txtName.ForeColor = Color.White
        Me.BackgroundImage = Image.FromFile(Application.StartupPath & "/res/UCItem_Wallpaper.png")
        isChecked = False
    End If
End Sub

Private Sub UC_Item_Click(sender As Object, e As EventArgs) Handles MyBase.Click
    toggle_color()
End Sub

Private Sub TxtName_Click(sender As Object, e As EventArgs) Handles txtName.Click
    toggle_color()
End Sub

代码:Form1.vb

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim UCItem As UC_Item

    flowItems.SuspendLayout()
    For i As Integer = 0 To items.Count - 1
        UCItem = New UC_Item
        UCItem.Tag = "UCItem" & i
        UCItem.txtName.Text = items(i).ToString
        flowItems.Controls.Add(UCItem)
        UCItem.Show() : UCItem.Visible = True
        AddHandler(UCItem.Click), AddressOf UCItem_Click
    Next
    flowItems.ResumeLayout()

End Sub

Private Sub UCItem_Click(sender As Object, ByVal e As EventArgs)
    ' -- not working part --
    ' If sender.isChecked = True Then
    '        sender.isChecked = False
    '  else
    '        sender.isChecked = True
End Sub

尝试

我尝试过传递“ UCItem作为sender.Tag”,但这也不起作用。在点击事件中,我无法访问发件人的.Tag和.Name属性。

感谢您的帮助!

0 个答案:

没有答案