Annoying .NET SP1 GroupBox and FlatStyle.System bug
I encountered this nasty .NET 1.1 SP1 bug in the Windows.Forms groupbox control yesterday, and unfortunately the workaround is not that straightforward to implement in reality.
My own less-than-perfect workaround is instead to disable FlatStyle on nested groupboxes. Here's the method I use to apply the styles:
#region SetObjectPropertyValue /// <summary> /// Attempts to set the value of a property of an object. /// Returns true if successful, false if not. /// </summary> /// <param name="objectInstance">The instance of the object</param> /// <param name="propertyName">The name of the property</param> /// <param name="propertyValue">The desired value of the property</param> /// <returns>True if successful, false if not.</returns> public static bool SetObjectPropertyValue(object objectInstance, string propertyName, object propertyValue) { bool isSet = false; try { //use reflection to attempt to set the FlatStyle of controls Type controlType = objectInstance.GetType(); //attempt to get the Control's specified property PropertyInfo prop = controlType.GetProperty(propertyName); //if it exists and is settable, set it if (prop != null && prop.CanWrite) { prop.SetValue(objectInstance, propertyValue, null); isSet = true; } } catch {} return isSet; } #endregion (SetObjectPropertyValue) #region SetFlatStyleSystem /// <summary> /// Method used recursively to set the FlatStyle property to system /// for all descendants of a control. Called from the form's constructor. /// </summary> /// <remarks> /// Originally copied from Chris Sells' Windows Forms Programming in C#, /// then embellished by Oskar Austegard (added Reflection). /// Requires that the main form's Main() method includes the line /// <code>Application.EnableVisualStyles();</code> /// prior to showing any UI. /// </remarks> /// <param name="parent">Control to start with</param> public static void SetFlatStyleSystem(Control parent) { Application.DoEvents(); //loop through any & all child controls foreach(Control control in parent.Controls) { //don't do this for labels (changes their vertical alignment) //and for groupboxes contained within other groupboxes (which due to a bug render with a large font) if (!(control is Label || (control is GroupBox && control.Parent is GroupBox))) { SetObjectPropertyValue(control, "FlatStyle", FlatStyle.System); } //Set contained controls' FlatStyle as well SetFlatStyleSystem(control); } } #endregion
0 Comments:
Post a Comment
<< Home