开发者

Winforms Extended Control Properties

I'm extending a Winforms Label control. (CustomLabel). Here's the definition:

public class CustomLabel: Label  
public CustomLabel():base()  
  {  

  }  

I'd like to change the label's default text. it's always CustomLabel1, CustomLabel2, etc.

I tried base.Text = ... and this.Text=... in the constructor. Also tried:

[DefaultValue(typeof(string), "MyDesiredText")]
public override string Text
{
    get
    {
        return base.Text;
    }
    set
    {
        base.Text = value;
    }
}

But no luck.

And one more thing: It seems like Autosize property doesn't work as expected and provides 1 character less space than necessary to view the custom label control for the first time. For example, the default text is: CustomLabel1 but I only see CustomLabel when I drag the control to the form. If I change the text, the Autosize property will show the whole text co开发者_StackOverflowrrectly.


A real fix requires replacing the designer for the control. That's quite hard to do, the LabelDesigner class in System.Design.dll is internal so you can't inherit it. The hacky way is this:

using System;
using System.Windows.Forms;

class CustomLabel : Label {
    public override string Text {
        get { return base.Text; }
        set {
            if (this.DesignMode && value.StartsWith("customLabel")) {
                value = DateTime.Now.ToString();   // whatever you want here
            }
            base.Text = value;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜