【问题标题】:C# UserControl - Get property value each control inside UserControl on Click eventC# UserControl - 在单击事件时获取 UserControl 内每个控件的属性值
【发布时间】:2018-01-18 04:07:56
【问题描述】:

我有一个这样的自定义 UserControl(它的名字是 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”。

这是我的 Click 事件代码:

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

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

【问题讨论】:

  • 我要做的第一件事就是在if(customView!=null) 上设置一个断点,看看sender 实际上是什么类型。一旦你知道你可能会知道下一步该做什么。
  • 感谢您的回复。 customView 为空,但发件人是 Picturebox。如果我将发件人投射到 PictureBox,我无法在第二列中获取 3 个 TextBoxes 的属性值
  • 您应该在用户控件内处理 PictureBox 的点击事件,并在发生这种情况时从 UserControl 引发一个点击事件。
  • 你能举个例子吗?我是 UserControl 的新手。

标签: c# winforms user-controls


【解决方案1】:

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

在您的用户控件中,您应该有这样的内容:

picturebox.Click += picturebox_click;


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

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

【讨论】:

  • 非常感谢 Zohar Peled。在你给我一些建议来解决我的问题之后。我在谷歌上搜索找到了解决方案,我得到了它。实际上,我一直在寻找您告诉我的内容 2 周,但似乎没有任何改变。直到我写了关键字“handle click event of control to UserControl”,我在微软找到了这个话题,我的问题已经解决了。
  • 很高兴为您提供帮助 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多