views:

117

answers:

1

Hi,

When we place a component on a Windows Form, the default behavior for the designer is to serialize a contructor call in the IntializeComponent method of the form.

Is there any way to have a custom serializer output the following code:

if (componentInstance == null)
   componentInstance = new componentClass();

instead of just:

componentInstance = new componentClass();

The reason is simply that the component is instantiated before the Form, and I want to pass it to one of the Form's constructors.

The component is designed to allow quick selection of properties (in the same way you add your DataBinding to Controls) at design time, but the call to the constructor in InitializeComponent() assumes I want to create a new instance when in fact, I already have a reference to it. By checking for null, then it would work both at design time and run time.

Thank you.

+1  A: 

It's simple really - don't use the Form Designer to add your component to the Winform. Instead manually add a member variable of the component type that you are after into the underlying code (.cs) file and handle it directly in code.

Added in response to your comment

As far as I am aware, there is no way in which you can avoid this behaviour for components placed at design time. You could delete references from initialise components method, but this may be overwritten by the designer at some point.

Taking into account your comment below, then I would suggest that you have a member variable on the form (as suggested above) and then set this to refer to the design time component if the runtime variable is null or the runtime variable if it isn't.

i.e.

CSomeComponentType liveComponent;

...
this.liveComponent = runtimeVariable;
if(this.liveComponent == null)
{
this.liveComponent = this.designTimeComponent;
}
ChrisBD
If I do that, then I lose design time support for that component.The best example I can give is that of a typed dataset. If I place a typed dataset component at design time on my form, then I can do all the databinding through the designer. But what if at runtime I want to pass an existing instance of the same typed dataset to the form ? Right now, I'd have to redo all the bindings in code.
mrlucmorin
Chris, thanks for your help, but this won't work as I'd lose all the bindings established in the InitializeComponents() method. I'm working on a CodeDOM solution, and I'm almost there.
mrlucmorin