13

I have a UserControl with a public property using the following attributes:

[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

I have tried deleting the owner form, re-creating a fresh form in Visual Studio 2010, and adding this UserControl to the form. It keeps adding a line like the following in the Designer file:

this.vMyUserControl.MyProperty = ((MyNamespace.MyClass)(resources.GetObject("vMyUserControl.MyProperty")));

This crashes my application because this property is not designed to be created by serialization.

Trevor Elliott
  • 11,292
  • 11
  • 63
  • 102

4 Answers4

13

Making the property read only at design time will prevent it being serialized into the resx file. Strangely if MyType happens to be a collection the read only is ignored by the designer and you can still set the property at design time even though the property isn't written out into the resx so it's best to make the property not browsable too.

[ReadOnly(true)]
[Browsable(false)]
public MyType MyProperty
{
    get { return _MyProperty; }
    set { _MyProperty = value; }
}
David Ewen
  • 3,632
  • 1
  • 19
  • 30
  • 1
    I'd just like to share that a colleague recommended this solution for when viewing a WinForm designer causes Visual Studio to crash. Set all custom public properties with these attributes which will prevent the designer from causing VS to crash. – TheLegendaryCopyCoder Sep 22 '14 at 09:49
  • I wish this attribute existed in the compact framework. :( – reirab Oct 15 '15 at 17:45
  • I had to use the fully-qualified name: in VS 2013 (VB) – Azura Oct 20 '15 at 18:04
5

Use [DesignerSerializationVisibilityAttribute ( Visibility = Hidden )]

MSDN Article

Nour
  • 5,252
  • 3
  • 41
  • 66
2

Try using a private field with the property's accessor methods along with the [field: NonSerialized] attribute:

[field: NonSerialized]
private MyType _MyProperty;

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public MyType MyProperty
{
    get
    {
        return _MyProperty;
    }
    set
    {
        _MyProperty = value;
    }
}
Mejwell
  • 716
  • 1
  • 6
  • 17
1

I failed to find a real solution, but a workaround instead...

I had to go into the Form.resx file and locate the data/value key pair that it was deserializing into my public property. I manually deleted the XML pair contents and then I was able to run the application.

This allowed my application to build and run without errors. Everything else I tried (including deleting the container form for my UserControl and re-creating it repeatedly) did not work.

Trevor Elliott
  • 11,292
  • 11
  • 63
  • 102