我试图从ToolStripLabel继承:
public class SeparatorLabel : ToolStripLabel
{
public SeparatorLabel() : base()
{
Margin = new Padding(5, 0, 5, 0);
Text = "ABC";
}
}
但是,当我在表单上放置这样的控件时,Text
属性取自在设计器的属性网格中输入的值。
当然,这是预料之中的,因为我的构造函数在设置属性网格属性之前被调用(形式为InitializeComponent()
),所以我的值会被覆盖。
问题是 - 从现有控件继承时实现此类行为的标准做法是什么?
我实现它的方法是覆盖Text
属性以包含空的setter,当我想更新控件Text
时,我设置base.Text
手动:
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 { }
}
}
这有效,但我不确定这是否是最佳做法。有没有更传统的方法来实现我的需要?
答案 0 :(得分:0)
您的示例无法编译,因为您的构造函数与您的类不同。
您还可以查看DesignerSerializationVisibility属性,并将其设置为Hidden
。
public SeparatorLabel() {
base.Margin = new Padding(5, 0, 5, 0);
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new Padding Margin {
get { return base.Margin; }
set {
throw new Exception("This property is read only.");
}
}