问题
Before I begin, it seems a similar/same question might have been asked before here, however no definitive answer exists.
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 = "";
}
}
My question is, How do I prevent the designer from automatically assigning the Text
property?
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.
回答1:
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.
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);
}
}
}
来源:https://stackoverflow.com/questions/35790863/how-to-prevent-winforms-designer-from-setting-text-property-to-instance-name