【问题标题】:How can I create a single event handler for many many pictureBoxes on MouseEnter?如何在 MouseEnter 上为许多图片框创建单个事件处理程序?
【发布时间】:2009-12-14 16:18:44
【问题描述】:

我的计划是创建一个单独的活动:

"好的,鼠标进入一个注册的pictureBox,根据发送者的名字加载X图片。"

处理这个问题的最佳方法是什么?

要不要创建一个字典,名字为key,图片资源的位置为value?

这是我目前所拥有的:

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>();

这不起作用。

【问题讨论】:

    标签: c# .net winforms dictionary


    【解决方案1】:

    你已经做到了。几乎 - 见下文

    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)           
    }
    

    【讨论】:

      【解决方案2】:

      通常我会看到一个用于此的 switch 语句。

      在你的 HeroMouseEnter 方法中

      PictureBox sendingBox = (PictureBox)sender;
      Switch(sendingBox.Name)
      {
          case "MyPicture":
              //Set picture here
              break;
          case "MyPicture2":
              //Next picture....
              break;
      }
      

      此外,如果您的图像已经在资源中,那么尝试为图像创建字典很可能会更加浪费,因为这只是重复。

      【讨论】:

        【解决方案3】:

        制作您自己的事件处理程序类,该类具有对应于图像名称的实例变量。然后你的代码看起来像......

        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);
            }
        

        或者更好的是,您可以传入 hero 本身(而不是字符串),并且该类会知道如何将 hero 转换为相应的图像。

        【讨论】:

          猜你喜欢
          • 2013-12-24
          • 2015-01-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-04
          • 2014-02-26
          • 1970-01-01
          相关资源
          最近更新 更多