问题
I want to make a custom property for a windows form browsable during design-time but none of my efforts have panned out to success. The obvious solution would seem to be to set the browsable attribute to true:
[Browsable(true),
EditorBrowsable(EditorBrowsableState.Always),
Description("Custom Border Colour"),
Category("Custom")]
public Color BorderColour
{
get
{
return bCol;
}
set
{
bCol = value;
}
}
But this doesn't work. I have done it numerous time for custom controls and it works like a charm, in fact, I don't even need to add the attributes because the default is true. This codeproject article seems to do what I want, which is what I described above. MSDN is also a dead end, or I don't know what to search for.
I have tried to add the code to Form1.cs
and From1.Designer.cs
but nothing works.
Is there something I am missing, like some property I need to set for the form to allow for this, or is it just impossible?
I am using Visual Studio Express 2013, if this would influence the outcomes in any way.
EDIT: Attempts after Reza's answer: A more detailed question on this topic is asked in this question as per Reza's suggestion.
回答1:
Short answer
You should add the property to base class of your form, then you can see it in designer when you open the child form:
public class Form1 : BaseForm
{
public Form1()
{
InitializeComponent();
}
}
public class BaseForm : Form
{
//The property is not visible in designer of BaseForm
//But you can see it in designer of Form1
public string SomeProperty {get;set;}
}
The reason behind this behavior
The reason is in the way that designer works. When the designer shows a form at design time, in fact it creates an instance of the base class of the form and shows its properties. So having public class Form1:Form
in designer, what you see in designer is actually an instance of Form
class and the instances of controls which values of properties has been set using using InitializeComponent
method of Form1
and also controls which are added using InitializeComponent
method of Form1
.
Also for user controls, you can not see your custom properties in the designer of your user control, because the properties that you can see in designer of your user control, is properties of it's base class. But when you put an instance of your user control on a form, you will see properties of that instance which is properties of your UserControl1
.
Properties of the root element of your designer are properties of base class of the root element. But the values are exactly those which are set in InitializeComponent
.
To find more information and see an interesting example of how the designer works, you can take a look at this post or this one.
来源:https://stackoverflow.com/questions/36715648/custom-browsable-property-for-form-at-design-time