[英]How to define default control properties?
我希望添加到其中一个表单的每个文本框看起来都一样,并具有相同的属性。 以文本框为例,我也希望将其用于按钮和组合框。 我的问题是如何为每个控件定义一组默认属性。 我也可以对表格进行处理吗?
一种解决方案是通过从基本控件继承并使用DefaultValue
属性修饰属性来创建自己的控件库。 例如:
public class MyTextBox: TextBox
{
public MyTextBox()
{
Text = "Hi";
}
[DefaultValue("Hi")]
public new string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
}
}
在new
关键字用于因为属性被重新定义。
为每个控件创建一个自定义类。 例如,如果您想要显示“ hello world”的文本框,则可以使用它。
public class NewTextBox : TextBox
{
//The constructor, called for every new instance of the class.
public NewTextBox()
{
Text = "hello world";
}
}
然后要在您的表单中使用它,您需要像这样调用一个新实例。
NewTextBox tb = new NewTextBox();//Create new text box
Controls.Add(tb);//Add text box to form.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.