C# UserControl - 在 Click 事件中获取 UserControl 中每个控件的 属性 值

C# UserControl - Get property value each control inside UserControl on Click event

我有一个这样的自定义用户控件(它的名称是 TP1CustomListView):

我使用了一个 2 列的 TableLayoutPanel 来保存一张图片(在第一列)和另一个 TableLayoutPanel(在第二列)。第二列中的 TableLayoutPanel 有 3 行可容纳 3 个 TextBox。

我在 UserControl 中为 PictureBox 编写了一个 Click 事件,如下所示:

 //events
        public new event EventHandler Click
        {
            add { picbox.Click += value; }
            remove { picbox.Click -= value; }
        }

在 Form1 中,我有 10 个用户控件,就像我附在主题顶部的图片一样。我已经为我的 Form1 中的所有 UserControl 编写了一个 Click 事件。我试图将每个 UserControl 的发件人投射到 Click 上,以在该 UserControl 中获取 3 个 TextBox 的 3 个值。但是我得到的结果是"NULL".

这是我的点击事件代码:

  public Form1()
        {
            InitializeComponent();
            foreach (Control c in this.Controls)
            {               
                TP1CustomListView ctLV = c as TP1CustomListView;
                if (ctLV != null)
                {
                    ctLV.Click += ctLV_Click;

                }
            }
        } 

  void ctLV_Click(object sender, EventArgs e)
        {

            TP1CustomListView customView = sender as TP1CustomListView;

              if(customView!=null)
              {
                  MessageBox.Show(customView.subtbTitle.Text + customView.subtbContent.Text + customView.subtbFooter.Text);
              }
        }

这是我的 TP1CustomListView (UserControl) 中的构造函数和子控件:

 //sub controls
        public PictureBox subPicbox;
        public TextBox subtbTitle;
        public TextBox subtbContent;
        public TextBox subtbFooter;
        public TP1CustomListView()
        {
            InitializeComponent();
            subtbTitle = txtTitle;
            subtbContent = txtContent;
            subtbFooter = txtFooter;
            subPicbox = picbox;
            tableLayoutPanel1.Dock = DockStyle.Fill;
        }

希望大家能给我一些建议或解决我的问题。 谢谢!

您应该在用户控件中处理 PictureBox 的点击事件,并在发生这种情况时从 UserControl 引发点击事件。

在你的用户控件中你应该有这样的东西:

picturebox.Click += picturebox_click;


private void picturebox_click(object sender, EventArgs e)
{
    var handler = this.Click;
    if(handler != null)
    {
        handler(this, e);
    }
}

这样,您对图片框的点击会触发对用户控件的点击,而该点击就是您在表单中实际监听的内容。