我的计划是创建一个单一的活动:
“好的,鼠标进入已注册的pictureBox,根据发件人名称将X图片加载到其上。”
处理此问题的最佳方法是什么?
我应该创建一个名称为key的字典,以及图片资源的位置作为值吗?
这是我到目前为止所拥有的:
private void SetPictureBoxEvents()
{
Andromeda.MouseEnter += new EventHandler(HeroMouseEnter);
Engineer.MouseEnter += new EventHandler(HeroMouseEnter);
Nighthound.MouseEnter += new EventHandler(HeroMouseEnter);
Swiftblade.MouseEnter += new EventHandler(HeroMouseEnter);
}
void HeroMouseEnter(object sender, EventArgs e)
{
//My picture box is named Andromeda. I'm going use that name
// as a key is a Dictionary and pull the picture according to the name.
//This is to make a generic event to handle all movements.
//Any help?
// ((PictureBox)sender).Image =
}
我怎么能在我的资源中为图像位置创建一个字典。:
Dictionary<string, TestProject.Properties.Resources> HeroList
= new Dictionary<string, TestProject.Properties.Resources>();
这不起作用。
答案 0 :(得分:4)
你已经做到了。几乎 - 见下文
void HeroMouseEnter(object sender, EventArgs e)
{
//My picture box is named Andromeda. I'm going use that name
// as a key is a Dictionary and pull the picture according to the name.
//This is to make a generic event to handle all movements.
//Any help?
((PictureBox)sender).Image = GetImage(((PictureBox)sender).Name)
}
答案 1 :(得分:0)
通常我会看到一个用于此的开关语句。
在HeroMouseEnter方法中
PictureBox sendingBox = (PictureBox)sender;
Switch(sendingBox.Name)
{
case "MyPicture":
//Set picture here
break;
case "MyPicture2":
//Next picture....
break;
}
此外,如果您的图片已经在资源中,那么尝试为图像创建字典可能会更加浪费,因为这只是重复。
答案 2 :(得分:0)
创建自己的事件处理程序类,其中包含与图像名称对应的实例变量。然后你的代码看起来像......
private void SetPictureBoxEvents()
{
Andromeda.MouseEnter += new EventHandler(new HeroMouseHandler("Andromeda.jpg").HeroMouseEnter);
Engineer.MouseEnter += new EventHandler(new HeroMouseHandler("Engineer.jpg").HeroMouseEnter);
Nighthound.MouseEnter += new EventHandler(new HeroMouseHandler("Nighthound.jpg").HeroMouseEnter);
Swiftblade.MouseEnter += new EventHandler(new HeroMouseHandler("Swiftblade.jpg").HeroMouseEnter);
}
或者更好的是,您将传递英雄本身(而不是字符串),并且该类将知道如何从英雄转换为相应的图像。