如何防止Winforms Designer将Text属性设置为实例名称 [英] How to prevent winforms designer from setting Text property to instance name

查看:49
本文介绍了如何防止Winforms Designer将Text属性设置为实例名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开始之前,在假设我有一个自定义的winforms控件,该控件将覆盖 Text 属性:

Suppose I have a custom winforms control which overrides the Text property:

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

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

我的问题是,如何防止设计人员自动分配 Text 属性?

My question is, How do I prevent the designer from automatically assigning the Text property?

在创建 MyControl 的实例时,设计人员会自动将 Text 属性分配给控件实例的名称​​ eg ,"MyControl1","MyControl2",.理想情况下,我希望将text属性设置为默认值,即一个空字符串.

When instances of MyControl are created, the designer automatically assigns the Text property to the name of the control instance, e.g., "MyControl1", "MyControl2", etc. Ideally, I would like the text property to be set to its default, an empty string.

推荐答案

设计者在InitializeNewComponent 中设置控件的 Text 属性.msdn.microsoft.com/zh-CN/library/system.windows.forms.design.controldesigner(v=vs.110).aspx"rel =" nofollow> ControlDesigner .
您可以为控件创建一个新的设计器并覆盖该方法,并在调用基本方法后,将 Text 属性设置为空字符串.

The designer sets Text property of control in InitializeNewComponent of ControlDesigner.
You can create a new designer for your control and override that method and after calling base method, set the Text property to empty string.

通过这种方式,您的控件以空的 Text 属性开始,并且还可以在设计时使用属性网格更改 Text 的值.

This way your control starts with an empty Text property and also you can change the value of Text using property grid at design-time.

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

这篇关于如何防止Winforms Designer将Text属性设置为实例名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆