开发者

What's the common ancestor of visual elements in C#?

I have a hard time believing that there isn't an answer here but it certainly looks like it doesn't exist.

I am trying开发者_开发百科 to iterate over everything on the form and set the visible and enabled properties based on the tag value. I find the reek of an absolutely duplicated routine between the routine iterating the controls and the routine iterating the menus--while both classes have visible, enabled and tag properties they appear to be separate items.

As far as I can tell the tree only converges at Component--but this lacks the visual properties.


That's correct, there is no common ancestor. The ToolStripMenuItem class is derived from ToolStripItem, the base class for many derived classes that are parts of a MenuStrip or a ToolStrip. They are special because they are not derived from Control. They are window-less controls, they don't have a Handle property. Which is the key property of the Control base class.

This is an optimization, the Control derived classes are expensive. They need a native Windows window, a heavy operating system object with lots of overhead. Really evident when you put, say, 50 buttons on a form. You can see it paint.

Duplicating this logic is thus normal. Using the Tag property to control state isn't.


There is no common ancestor, however you can circumvent this by using the dynamic type. For example:

object control = new Button() { Tag = "Whatever" };
object menuItem = new ToolStripMenuItem { Tag = "Something else" };
object tag1 = (control as dynamic).Tag;
object tag2 = (menuItem as dynamic).Tag;
// Do something with tag1 and tag2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜