How Do I Stop Visual Studio from Generating Setter Calls in my UserControl?
I have created a couple of controls that inherit from UserControl for my Winform application. They both have parameterless constructors, as is required. When I drop them onto my main form, I get an error in Visual Studio at design-time where it cannot render the form.
What I discovered is that, in the form's Designer.cs file, where my control is instantiated, the IDE is placing a line there that calls one of my se开发者_StackOverflow社区tters. BlockKey = 0
. Well, the code behind the setter is calling some other code, and quickly a NullReferenceException gets thrown because the form's not running; that other code is not prepared to produce anything at that point.
If I manually remove the setter line, the error goes away. But closing and re-opening, or re-compiling, the IDE puts the line back in again. I tried decorating, inside the UserControl, the setter with [DefaultValue(false)]
, thinking this would suppress the design-time call to the setter, but it did not.
How can I get rid of that line in the Designer? Or am I expected to do write some preventative code inside the setter instead?
You should use the DesignerSerializationVisibilityAttribute
attribute on your property with it set to Hidden
.
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int BlockKey
{
get { return 0; }
set { /* Do something */ }
}
Alternatively if you need more specific logic (i.e. only serialize in certain conditions) then you must create a function that returns a bool and has a specific name in the format of bool ShouldSerialize*PropertyName*()
bool ShouldSerializeBlockKey()
{
return false;
}
(NOTE: I forget whether this function must be public or not...)
What you're looking for is the DesignerSerializationVisibilityAttribute
. This controls whether or not the designer will serialize out default values for a particular attribute or not
- Documentation
If you specify the properties as Hidden
the designer won't add values for them
精彩评论