加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何设置设计时属性默认值?

发布时间:2020-12-15 17:37:20 所属栏目:百科 来源:网络整理
导读:根据MSDN( http://msdn.microsoft.com/en-us/library/system.windows.forms.label.autosize.aspx),有关于Label的AutoSize属性的说明: When added to a form using the designer,the default value is true. When instantiated from code,the default value
根据MSDN( http://msdn.microsoft.com/en-us/library/system.windows.forms.label.autosize.aspx),有关于Label的AutoSize属性的说明:

When added to a form using the designer,the default value is true. When instantiated from code,the default value is false.

问题是:如何覆盖Label控件并将其AutoSize属性的设计时默认值设置为false?

(更新)

这不起作用:

class MyLabel : Label
{
    const bool defaultAutoSize = false;

    public MyLabel()
    {
        AutoSize = defaultAutoSize;
    }

    [DefaultValue(defaultAutoSize)]
    public override bool AutoSize
    {
        get
        {
            return base.AutoSize;
        }
        set
        {
            base.AutoSize = value;
        }
    }
}

解决方法

只需使用继承.但是,您必须使用自定义标签而不是系统标签.
public class MyLabel:Label
{
    public MyLabel():base()
    {
        base.AutoSize = false;
    }
}

您可以将其直接放入代码中并修改代码,如下所示.或者,您可以将此类放入其自己的库中,然后您可以将其加载到工具箱中并像使用任何其他组件一样使用.

为了在工具箱中工作,您似乎需要覆盖InitLayout,如下所示,并向AutoSize属性添加一个属性,以便它不会序列化到设计器中:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    [DefaultValue(false)]
    public override bool AutoSize
    {
        get
        {
            return base.AutoSize;
        }
        set
        {
            base.AutoSize = value;
        }
    }

    protected override void InitLayout()
    {
        base.InitLayout();
        base.AutoSize = false;
    }

如果您没有使用工具箱,那么一旦将正常标签放到表单上,就需要进入[Form] .Designer.cs并找到并修改标签:

this.label1 = new MyLabel();// new System.Windows.Forms.Label();

//this.label1.AutoSize = true;

您必须删除预设的AutoSize属性,因为当您删除标签时,它会将其设置在设计器中,即使您将标签实例化更改为您的类型,手动AutoSize设置也将覆盖您的默认值

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读