我在类HUD.cs中有以下方法,它有辅助方法。假设以下方法检查所有控件TAG是否为“required”并突出显示它们找到的那些。
如果我从UserControl调用它并且要突出显示的Control不包含在GroupBox中,但是当它们是TAG时似乎没有遇到它。想法?
这是方法 - >
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,
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);
}
}
}
}
答案 0 :(得分:0)
这应该是正确定位标签(您可以通过调试器中的步进来检查),所以我认为问题更可能是绘图。有几件事可能会导致问题。
首先,Control.Bounds属性相对于父元素。因此,当您递归到子控件集合时,矩形将被绘制在“错误”坐标处:例如,如果子控件位于组框的左上角,其边界可能是(0,0,100,100),但是实际上,我希望在组框坐标处绘制矩形。
其次,我相信子控件,因为它是一个单独的HWND,将出现在父控件的Graphics上下文的顶部。即你正在绘制父控件(UserControl说),但子控件(GroupBox说)高于那个,遮住你的绘图。
对于这两个问题,解决方案是获取子控件的图形上下文并将其传递给递归调用。