如何在构造函数中设置控件属性(Designer 的问题)
我试图从 ToolStripLabel 继承:
public class SeparatorLabel : ToolStripLabel
{
public SeparatorLabel() : base()
{
Margin = new Padding(5, 0, 5, 0);
Text = "ABC";
}
}
但是,当我在表单上放置这样的控件时,Text
属性将从设计器的属性网格中输入的值获取。
当然,这是预期的,因为我的构造函数在设置属性网格的属性(表单的 InitializeComponent()
)之前被调用,因此我的值被覆盖。
问题是 - 从现有控件继承时实现此类行为的标准做法是什么?
我实现它的方法是重写 Text
属性以包含一个空的 setter,当我想更新控件的 Text
时,我设置了 base。手动发送文本
:
public class SeparatorLabel : ToolStripLabel
{
public SeparatorLabel() : base()
{
Margin = new Padding(5, 0, 5, 0);
base.Text = "ABC";
}
[Browsable(false)]
public override string Text
{
get
{
return base.Text;
}
set { }
}
}
这可行,但我不确定这是否是最佳实践。有没有更传统的方法来实现我的需要?
I am trying to inherit from the ToolStripLabel:
public class SeparatorLabel : ToolStripLabel
{
public SeparatorLabel() : base()
{
Margin = new Padding(5, 0, 5, 0);
Text = "ABC";
}
}
However, when I place such a control on the form, the Text
property is taken from the value entered in the designer's property grid.
This is, of course, expected, since my constructor gets called before the property grid's properties are set (form's InitializeComponent()
), so my values get overwritten.
The question is - what is the standard practice to achieve such behavior when inheriting from existing controls?
The way I did implement it was to override the Text
property to include an empty setter, and when I want to update the control's Text
, I set the base.Text
manually:
public class SeparatorLabel : ToolStripLabel
{
public SeparatorLabel() : base()
{
Margin = new Padding(5, 0, 5, 0);
base.Text = "ABC";
}
[Browsable(false)]
public override string Text
{
get
{
return base.Text;
}
set { }
}
}
This works but I am not sure if that's the best practice. Is there any more conventional way to achieve what I need?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的示例无法编译,因为您的构造函数与您的类不同。
您还可以查看 DesignerSerializationVisibility 属性,然后设置将其设置为
隐藏
。Your example doesn't compile since your constructor is different than your class.
You can also look at the DesignerSerializationVisibility attribute, and set it to
Hidden
.