繁体   English   中英

如何防止winforms设计器将Text属性设置为实例名称

[英]How to prevent winforms designer from setting Text property to instance name

在我开始之前,似乎在之前可能会问过类似/相同的问题,但是没有明确的答案


假设我有一个自定义的winforms控件,它会覆盖Text属性:

public class MyControl : Control
{
    [DefaultValue("")]
    public override string Text
    {
        get { return base.Text; }
        set 
        {
            base.Text = value;
            ...
        }
    }

    public MyControl()
    {
        this.Text = "";
    }
}

我的问题是, 如何阻止设计器自动分配Text属性

当创建MyControl实例时,设计器会自动将Text属性分配给控件实例的名称, 例如 “MyControl1”,“MyControl2” 理想情况下,我希望将text属性设置为默认值,即空字符串。

设计者在ControlDesigner InitializeNewComponent中设置控件的Text属性。
您可以为控件创建新的设计器并覆盖该方法,并在调用基本方法后,将Text属性设置为空字符串。

这样,您的控件以空Text属性开始,您还可以在设计时使用属性网格更改Text的值。

using System.ComponentModel;
using System.Windows.Forms;
using System.Windows.Forms.Design;

[Designer(typeof(MyControlDesigner))]
public partial class MyControl: Control
{
}

public class MyControlDesigner : ControlDesigner
{
    public override void InitializeNewComponent(System.Collections.IDictionary defaultValues)
    {
        base.InitializeNewComponent(defaultValues);

        PropertyDescriptor descriptor = TypeDescriptor.GetProperties(base.Component)["Text"];
        if (((descriptor != null) && (descriptor.PropertyType == typeof(string))) && (!descriptor.IsReadOnly && descriptor.IsBrowsable))
        {
            descriptor.SetValue(base.Component, string.Empty);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM