[英]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.