【问题标题】:Toggle BorderStyle with a method. C#使用方法切换 BorderStyle。 C#
【发布时间】:2010-11-26 12:04:03
【问题描述】:

有谁知道我怎么写“cardImage1.BorderStyle = BorderStyle.Fixed3D;”无需明确声明“cardImage1”?

我正在尝试将其放入一个方法中,这样我就不需要编写代码来在单击图片框时在两个边框样式之间切换,对于每个单独的图片框(有 52 个!)

例如对于当前的每个框,我需要在其 _click 事件中包含以下内容。

        if (cardImage1.BorderStyle == BorderStyle.None)
        {
            cardImage1.BorderStyle = BorderStyle.Fixed3D;
        }
        else
        {
            cardImage1.BorderStyle = BorderStyle.None;
        }

【问题讨论】:

    标签: c# .net methods properties


    【解决方案1】:

    假设这是在事件处理程序中,您应该将 sender 参数转换为 PictureBox 并直接对其进行操作。

    private void pictureBox_Click(object sender, EventArgs args)
    {
        var image = (PictureBox)sender;
        if (image.BorderStyle == BorderStyle.None)
        {
            image.BorderStyle = BorderStyle.Fixed3D;
        }
        else
        {
            image.BorderStyle = BorderStyle.None;
        }
    }
    

    然后,您将对PictureBox 的所有实例使用相同的事件处理程序。

    【讨论】:

      【解决方案2】:

      您可以编写一个方法来处理所有图片框的点击,而不是为每个图片框创建一个处理程序:

       protected void onClickHandler(object sender, EventArgs e)
       {
          if (((PictureBox)sender).BorderStyle == BorderStyle.None)
          {
              ((PictureBox)sender).BorderStyle = BorderStyle.Fixed3D;
          }
          else
          {
              ((PictureBox)sender).BorderStyle = BorderStyle.None;
          }
      
      }
      

      您还可以编写一个循环来遍历表单上的所有控件并将事件处理程序附加到所有图片框(如果可能的话)

      // in your form load event do something like this:
      foreach(Control c in this.Controls)
      {
          PictureBox pb = c as PictureBox;
          if(pb != null)
             pb.Click += new EventHandler(onClickHandler); // where onClickHandler is the above function
      }
      

      当然,如果表单上有其他图片框,解决方案是将 52 个您感兴趣的图片框放在一个面板中,而不是遍历表单中的所有控件 (this.Controls ) 只遍历面板中的控件 (thePanelControl.Controls)

      【讨论】:

      • 非常感谢大家,这个特殊的问题已经解决了,他背后的想法将在项目中多次使用。你不知道我昨晚为此绞尽脑汁了多久!
      • 我很高兴能帮上忙 :)
      【解决方案3】:

      创建一个新类型MyPictureBox 并处理点击事件。将所有PictureBox 替换为MyPictureBox

      class MyPictureBox : PictureBox
      {
          protected void this_Click(object sender, EventArgs e)
          {
              if (this.BorderStyle == BorderStyle.None)
              {
                  this.BorderStyle = BorderStyle.Fixed3D;
              }
              else
              {
                  this.BorderStyle = BorderStyle.None;
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多