|
I have a recursive function on my form that sets backgrounds of all Controls on it to Color.Transparent . It was a happy function until the moment I put a DataGridView on the form. DataGridView doesn't support transparent color, and the function blew up in an exception.
I could put an empty try catch around the color assignment line, but that is just way too ugly of a "solution".
The only way to determine whether a Control supports transparent background is to call the GetStyle() function. Too bad it's protected. Is there any good reason for this function being protected and not public? No way someone is going to inherit from every control just to get to those flags.
As usual, Reflection saves the day. Write an extension method that gets the flag in question. Well, it would probably make sense to write an extension that exposes the GetStyle(), but I wanted more readability in my code.
Anyway, this is the extension method:
public static bool SupportsTransparentBackColor(this Control control)
{
Type t = control.GetType();
MethodInfo miGetStyle = t.GetMethod(
"GetStyle",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy,
null,
new Type[] { typeof(ControlStyles) },
null);
return (bool)miGetStyle.Invoke(control, new object[] {
ControlStyles.SupportsTransparentBackColor
});
}
And that is how it's used (I wish there were extension Properties too)
if (ctl.SupportsTransparentBackColor())
{
ctl.BackColor = Color.Transparent;
}
|
|
|
|