I have a user control that has a few public properties, one is an object where I set [Browseable(false)]. When I add this control in Visual Studio’s designer the generated code sets this object to null.
public class Foo : System.Windows.Forms.UserControl
{
[Browsable(false)]
public object Bar { get; set; }
[Browsable(true)]
public bool IsSomething { get; set; }
...
}
private void InitializeComponent()
{
...
this.foo = new Foo();
this.foo.IsSomething = false;
this.foo.Bar = null;
...
}
I don’t understand why Visual Studio would want to do that and I’m curious if there is a way to mark it so that it doesn’t set it. I discovered this by setting the object to something in the constructor only to watch the contol’s parent set it back to null.
There are a couple of options here. First, BrowsableAttribute only determines whether the property shows up in the property grid. To prevent the property from being serialized at all, use the DesignerSerializationVisibilityAttribute:
Second, if you want the property to be serialized, but only when the user has actually changed the value, use the DefaultValueAttribute:
This will cause the property to only be serialized if it is different from its default value. This also has other positive side-effects
There are more advanced techniques for controlling property interaction with the designer (Google “ShouldSerialize”), but these attributes should get you most of the way there.