在我开始之前,似乎在 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/