Tuesday, August 01, 2006

How to get the type of the component being designed in Visual Studio .Net

What is the proper way to get, from within your designer component, the type of the component being designed? (Hm, if that one is the designer, the other one is surely the designee?)

1. this.Component.GetType() doesn't work because Visual Studio sneakily instantiates not the class you design but the base class (why does it do this? Beats me).

2. Wow, there's a RootComponentClassName in IDesignerHost, beautiful! Or maybe not.

The guys at msdn say that RootComponentClassName "Gets the fully qualified name of the class being designed". Oh, wait... No, they say it's property value is "The fully qualified name of the base component class". On the same page. So which one is it? When you access the property, you discover that the name isn't qualified at all. So you get the unqualified name of the class being designed (not the base one). Super, but what good is an unqualified class name?

3. Ok, so it's an undocumented/badly documented feature. This guy has it figured out:

The RootComponentClassName is not initialized until the designer host has completed loading (which means, when IDesignerHost.LoadComplete is triggered). So, that's it: handle LoadComplete, and from LoadComplete get the RootComponentClassName.