Winforms 扩展控件属性

发布于 2024-10-06 20:18:31 字数 693 浏览 0 评论 0原文

我正在扩展 Winforms Label 控件。 (自定义标签)。定义如下:

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

  }  

我想更改标签的默认文本。它始终是 CustomLabel1CustomLabel2 等。
我在构造函数中尝试了 base.Text = ...this.Text=... 。也尝试过:

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

但没有运气。
还有一件事:Autosize 属性似乎没有按预期工作,并且提供的空间比第一次查看自定义标签控件所需的空间少 1 个字符。例如,默认文本为:CustomLabel1,但当我将控件拖动到窗体时,我只看到 CustomLabel。如果我更改文本,“自动调整大小”属性将正确显示整个文本。

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 correctly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北座城市 2024-10-13 20:18:32

真正的修复需要更换控件的设计者。这很难做到,System.Design.dll 中的 LabelDesigner 类是内部的,因此您无法继承它。黑客的方法是这样的:

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;
        }
    }
}

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;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文