【问题标题】:How to set control properties in constructor (problems with Designer)如何在构造函数中设置控件属性(Designer 的问题)
【发布时间】:2012-03-12 18:26:57
【问题描述】:

我正在尝试从 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 { }
    }
}

这可行,但我不确定这是否是最佳做法。有没有更传统的方法来实现我的需要?

【问题讨论】:

    标签: c# inheritance constructor custom-controls overriding


    【解决方案1】:

    您的示例无法编译,因为您的构造函数与您的类不同。

    您也可以查看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.");
      }
    }
    

    【讨论】:

    • 我已经更正了示例中的错误(我没有直接从我的代码中复制,因此构造函数名称无效)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多