使 checkbox.Checked = True 其对应的 PictureBox 被点击 [英] Make checkbox.Checked = True whose corresponding PictureBox is clicked

查看:32
本文介绍了使 checkbox.Checked = True 其对应的 PictureBox 被点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Windows 窗体中有 28 个复选框.每个框上方都有 PictureBox.当用户点击一个PictureBox时,我想把PictureBox的BackColor改成绿色,并使其对应的CheckBox.Checked = True

I have 28 CheckBoxes in a windows form. Each box has PictureBox above it. When the user clicks on a PictureBox, I want to change the BackColor of the PictureBox to green, and make its corresponding CheckBox.Checked = True

我使用的代码:

Private Sub PictureBox1_Click
    PictureBox1.BackColor = Color. Green 
    CheckBox1.Checked = true 

对于 28 岁来说,这将是一个漫长的过程.有什么简单的办法吗?

For 28 it will be a lengthy process. Is there any easy solution?

推荐答案

以编程方式将 MouseClick 偶数处理程序添加到 Form_Load 中的所有图片框.事件处理程序将解析发送者 (PictureBox) 并根据相应控件的名称以相同索引结尾的事实找到 CheckBox.当表单关闭时移除处理程序.

Programmatically add MouseClick even handlers to all your PictureBoxes in Form_Load. The event handler will parse the sender (PictureBox) and find the CheckBox based on the fact that the corresponding controls' names end in the same index. Remove the handlers when the form closes.

Private pictureBoxPrefix As String = "PictureBox"
Private checkBoxPrefix As String = "CheckBox"

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix))
        AddHandler pb.MouseClick, AddressOf PictureBox_MouseClick
    Next
End Sub

Private Sub PictureBox_MouseClick(sender As Object, e As MouseEventArgs)
    Dim index = Integer.Parse(pb.Name.Replace(pictureBoxPrefix, ""))
    Dim pb = CType(sender, PictureBox)
    Dim cb = CType(Me.Controls.Find($"{checkBoxPrefix}{index}", True).First(), CheckBox)
    pb.BackColor = Color.Green
    cb.Checked = True
End Sub

Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
    For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix))
        RemoveHandler pb.MouseClick, AddressOf PictureBox_MouseClick
    Next
End Sub

这篇关于使 checkbox.Checked = True 其对应的 PictureBox 被点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆