我已经用VB.NET编写了此代码,我需要将其转换为C#,但是我遇到了一些问题。
这是VB中的代码:
For Each c in Me.Controls
If TypeOf (c) Is PictureBox Then
CType(c,PictureBox).Image = icon;
AddHandler c.Click, AddressOf PictureBox10_Click
End If
所以基本上我想让它检查PictureBoxes并给它们一个图标,并使这些PictureBox具有与PictureBox10 Click事件相同的功能。
这是我用C#编写的代码:
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(System.Windows.Forms.PictureBox))
{
((PictureBox)c).Image = Properties.Resorces.available;
c.Click += new System.EventHandler(this.pictureBox10_Click);
}
}
它可以一直工作到图像部分,但是我无法使EventHandler
正常工作。
这也是PictureBox10 Click事件的作用:
private void pictureBox10_Click(object sender, EventArgs e)
{
if (pictureBox10.Image == Properties.Resorces.available)
pictureBox10.Image = Properties.Resorces.selected;
else if (pictureBox10.Image == Properties.Resorces.selected)
pictureBox10.Image = Properties.Resorces.available;
}
非常感谢您的帮助。
答案 0 :(得分:2)
可以使用System.Linq
扩展方法OfType
简化选择图片框的代码,该方法仅选择OfType
参数中指定的控件,并以该类型返回它们。另外,我们可以为所有这些控件分配一个公共事件处理程序:
foreach (PictureBox pb in Controls.OfType<PictureBox>())
{
pb.Image = Properties.Resorces.available;
pb.Click += PictureBox_Click; // Defined below
}
然后在事件处理程序中,将sender
强制转换为PictureBox
,以便我们有一个强类型的对象,该对象允许我们设置Image
属性:
private void PictureBox_Click(object sender, EventArgs e)
{
var thisPictureBox = sender as PictureBox;
// May not be necessary, but it's a good practice to ensure that 'sender' was actually
// a PictureBox and not some other object by checking if 'thisPictureBox' is 'null'
if (thisPictureBox == null) return;
if (thisPictureBox.Image == Properties.Resorces.available)
{
thisPictureBox.Image = Properties.Resorces.selected;
{
else if (thisPictureBox.Image == Properties.Resorces.selected)
{
thisPictureBox.Image = Properties.Resorces.available;
}
}