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

本文关键字:设置 属性 实例 文本 winforms 何防止 | 更新日期: 2023-09-27 18:37:15

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


假设我有一个重写 Text 属性的自定义 winforms 控件:

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 属性设置为其默认值,即空字符串。

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

设计器在

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