【发布时间】: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