简体   繁体   English

PictureBox上的MouseClick事件触发对应的CheckBox

[英]MouseClick event on PictureBox trigger corresponding CheckBox

My C# window forms application generate a list of CheckBox and PictureBox (in pair) at runtime.我的 C# window forms 应用程序在运行时生成 CheckBox 和 PictureBox(成对)列表。 I want it so that when I click on the PictureBox (ie a MouseClick event), the corresponding CheckBox is checked/unchecked.我想要这样当我点击 PictureBox(即 MouseClick 事件)时,相应的 CheckBox 被选中/取消选中。 How should I go about this?我应该如何 go 关于这个?

I would prefer to store pointer for corresponding checkbox in Tag property of PictureBox .我更愿意在PictureBoxTag属性中存储相应复选框的指针。 After that, you can use it in PictureBox click event handler:之后,您可以在 PictureBox 单击事件处理程序中使用它:

((sender as PictureBox).Tag as CheckBox).Checked = !((sender as PictureBox).Tag as CheckBox);

Don't forget to check Tag for null不要忘记检查nullTag

If you're generating the controls on the fly, I would prefer building an associated dictionary to store the pairs rather than using Tag.如果您正在动态生成控件,我宁愿构建一个关联的字典来存储这些对,而不是使用 Tag。

Dictionary<PictureBox, CheckBox> association = new Dictionary<PictureBox, CheckBox>();

// ---------------------------------------
// then, in your generation code

PictureBox pb = // init
CheckBox cb = // init

// whatever

association.Add(pb, cb);

// ---------------------------------------    
// then, in your click handler for picturebox

PictureBox pb = (PictureBox)sender;
CheckBox cb = association[pb];

cb.Checked = !cb.Checked;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM