Winforms 控件占位符
我正在尝试将 System.Windows.Forms.Control 添加到给定的表单控件集合中。我通过创建类型控制的私有字段,然后在构造函数中将该字段实例化为 System.Windows.Forms.Control 的新实例来实现此目的。
在运行时,我尝试通过执行以下代码示例中的操作,将 _placeholder 变量的类型更改为 TextBox。所以基本上我试图拥有一个 Control 类型的占位符,并在运行时将其更改为另一个控件,例如 TextBox 或 Label。我的问题是我的表格上没有显示任何内容?任何见解将不胜感激。
public class MyForm : Form
{
System.Windows.Forms.Control _placeholder = null;
public MyForm()
{
_placeholder = new System.Windows.Forms.Control();
this.Controls.Add(_placeholder);
ChangeToTextBox();
}
public void ChangeToTextBox()
{
_placeholder = new TextBox();
}
}
I am trying to add a System.Windows.Forms.Control to a given forms control collection. I do this by creating a private field of type control and then instantiating this field to a new instance of System.Windows.Forms.Control in the constructor.
At runtime I am trying to change the type of the _placeholder variable to a TextBox, by doing something like in the following code example. So basically I am trying to have a placeholder of type Control and change it to another control like a TextBox or Label at runtime. My issue is that nothing shows up on my form? Any insight would be appreciated.
public class MyForm : Form
{
System.Windows.Forms.Control _placeholder = null;
public MyForm()
{
_placeholder = new System.Windows.Forms.Control();
this.Controls.Add(_placeholder);
ChangeToTextBox();
}
public void ChangeToTextBox()
{
_placeholder = new TextBox();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如所写的,这是行不通的,因为原始占位符仍然是添加到控件的引用。您可以通过执行以下操作来修复它:
也就是说,如果这要进入表单上的同一位置,您可能需要考虑放置 Panel 那里,只需将文本框添加到面板即可。这将避免删除现有控件的需要,因为它只是添加一个控件。
This won't work, as written, because the original placeholder is still the reference added to the controls. You could fix it by doing:
That being said, if this is going to go into the same location on your form, you might want to consider putting a Panel there instead, and just adding the TextBox to the Panel. This will prevent the need to remove existing controls since it's just adding one in.
它不起作用,因为添加到 Controls 集合中的是您在构造函数中添加的
System.Windows.Forms.Control
实例。然后,您将_placeholder
指向的对象更改为文本框控件,但从未将该文本框添加到表单的Controls
集合中。It doesn't work because what's added to the Controls collection is the instance of
System.Windows.Forms.Control
that you added in the constructor. You then change the object that_placeholder
points to to a textbox control, but you never add that textbox to the form'sControls
collection.