Reputation: 375
I am stuck in a bit of marsh here, as I can't figure out a simple enough way to detect inherited user controls. Basically, I have a user control "UC",
public partial class UC : UserControl
which will work as a kind of template for common properties;
and some inherited user controls ("uc1","uc2","uc3", etc...)
public partial class uc1 : UC
*Purpose would be to list inherited controls and throw them in a container panel upon init.
My question: Can I detect/count/list them is some simple way (no 20+ line code stuff) or can it be done at all?
Any advice appreciated.
Developer ir training :D
Upvotes: 0
Views: 98
Reputation: 3935
Add a static counter to the base class. in the base class common constructor, or init method - call counter++ . and on its closed event- call counter--.
If you are not affraid to write a few more lines of code, than a singleon pattern to hold the counter is better.
Upvotes: 0
Reputation: 3262
Try something like this (this will traverse all existing assemblies, not the ones that haven't already been loaded. I also recommend doing something more elegant than this which involves more awareness of what you actually need to be doing. This is just brute force (and it costs time and resources too so run this only once, not once every millisecond)):
var query = from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where typeof(UC).IsAssignableFrom(type) && (type != typeof(UC))
let ctor = type.GetConstructor(Type.EmptyTypes)
where ctor != null
select type;
foreach (var type in query) {
var control = Activator.CreateInstance(type, nonPublic: true) as UC;
control.Parent = thePanel;
}
but beware of the logical flaw here: Each class that extends the UC
class will have 1 instance and 1 instance only. Also: how will you dynamically manage the positioning of these user controls in inside thePanel
?
Upvotes: 1
Reputation: 13600
If you know, where these controls are located (I mean an assembly), you can use use Reflection
to iterate through objects and test for the type.
Not sure if the resulting code will be 20 or less lines of code though, but it's the only way I know of...
Upvotes: 0