I have the below method in a class, HUD.cs, that has helper methods. The below method is suppossed to check all controls TAG for "required" and highlight those it finds.
It works fine if I call it from a UserControl and the Control's to be Highlighted are not contained in a GroupBox but when they are the TAG does not seem to come across. Ideas?
Here's the method-->
public static void HighlightRequiredFields(Control container, Graphics graphics, Boolean isVisible)
{
var borderColor = Color.FromArgb(173, 216, 230);
const ButtonBorderStyle borderStyle = ButtonBorderStyle.Solid;
const int borderWidth = 3;
Rectangle rect = default(Rectangle);
foreach (Control control in container.Controls)
{
if (control.Tag is string && control.Tag.ToString() == "required")
{
rect = control.Bounds;
rect.Inflate(3, 3);
if (isVisible && control.Text.Equals(string.Empty))
{
ControlPaint.DrawBorder(graphics, rect,
borderColor,
borderWidth,
borderStyle,
开发者_StackOverflow中文版 borderColor,
borderWidth,
borderStyle,
borderColor,
borderWidth,
borderStyle,
borderColor,
borderWidth,
borderStyle);
}
else
{
ControlPaint.DrawBorder(graphics, rect, container.BackColor, ButtonBorderStyle.None);
}
}
if (control.HasChildren)
{
foreach (Control ctrl in control.Controls)
{
HighlightRequiredFields(ctrl, graphics, isVisible);
}
}
}
}
That should be locating the Tags correctly (you can check this by stepping through in the debugger) so I think the problem is more likely with the drawing. There are a couple of things that might be causing problems here.
First, the Control.Bounds property is relative to the parent element. Therefore when you recurse into the child controls collection, the rectangles are being drawn at the "wrong" coordinates: for example, if a child control is at the top left of a group box its Bounds might be (0,0,100,100), but you'd actually want the rectangle to be drawn at the group box coordinates.
Second, I believe the child control, because it is a separate HWND, is going to appear over the top of the parent control's Graphics context. I.e. you are drawing on the parent control (the UserControl say), but the child control (the GroupBox say) is above that, obscuring your drawing.
For both of these issues the solution is to get the graphics context of the child control and pass that into the recursive call.
精彩评论