PictureBox上的鼠标单击事件触发相应的复选框。

3

我的C#窗体应用程序在运行时会生成一组复选框和图片框(成对出现)。我希望当我点击图片框时(即鼠标单击事件),相应的复选框被选中/取消选中。我该怎么做呢?

2个回答

1

我更倾向于在PictureBoxTag属性中存储对应复选框的指针。然后,在PictureBox点击事件处理程序中,您可以使用它:

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

不要忘记检查标签null的内容。

0
如果您正在动态生成控件,我建议使用相关的字典来存储键值对,而不是使用标签。
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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接