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

标签 c# winforms windows-forms-designer

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

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

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

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

我的问题是,如何防止设计器自动分配 Text属性(property) ?

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

最佳答案

设计师套装Text InitializeNewComponent 中的控制属性的 ControlDesigner .
您可以为您的控件创建一个新的设计器并覆盖该方法,并在调用基方法后,设置 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);
        }
    }
}

关于c# - 如何防止winforms设计器将Text属性设置为实例名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35790863/

相关文章:

javascript - Tab 进行验证码

c#-4.0 - 取消订阅用户控件中的事件的标准方法

c# - 将 'Which branch?' 字段添加到 TFS 中的工作项

c# - 如何通过 View 模型库访问所有 View 模型?

c# - 使用客户端 Web 服务时出现内容错误

c# - .NET Form close/dispose 不释放全局对象

c# - 使用 c# 将项目从 xml 填充到 Datagridview 的任何方法

c# - 为什么在 StreamReader.Read 周围使用 using() {} 允许之后删除文件?

C# [设计] 丢失了..只剩下.designer