【问题标题】:Tag property for Controls not carrying over to static method控件的标记属性未延续到静态方法
【发布时间】:2010-02-10 19:58:46
【问题描述】:

我在一个类 HUD.cs 中有以下方法,它具有辅助方法。下面的方法应该检查所有控件标签是否为“必需”并突出显示它找到的那些。

如果我从 UserControl 调用它并且要突出显示的控件不包含在 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);
                }
            }
        }
    }

【问题讨论】:

    标签: c# .net winforms controls


    【解决方案1】:

    这应该是正确定位标签(您可以通过在调试器中逐步检查)所以我认为问题更可能与绘图有关。这里有几件事可能会导致问题。

    首先,Control.Bounds 属性是相对于 parent 元素的。因此,当您递归到子控件集合时,矩形将在“错误”坐标处绘制:例如,如果子控件位于组框的左上角,其边界可能是 (0,0,100,100),但您'd 实际上希望在组框坐标处绘制矩形。

    其次,我相信子控件,因为它是一个单独的 HWND,将出现在父控件的 Graphics 上下文的顶部。 IE。您正在父控件(例如 UserControl)上绘图,但子控件(例如 GroupBox)在其上方,遮挡了您的绘图。

    对于这两个问题,解决方案是获取子控件的图形上下文并将其传递给递归调用。

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 2014-02-18
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多