2

我在应用程序中有一个用户表单。某些字段已验证。如果字段的值错误,则为此控件绘制红色边框。它是通过处理Paint此控件的事件来完成的。我扩展TextField并从这些类对象DateTimePicker中获取Paint事件。我上课有问题NumericUpDown。它确实会Paint正确触发事件,但会调用

ControlPaint.DrawBorder(e.Graphics, eClipRectangle, Color.Red, ButtonBorderStyle.Solid);

完全什么都不做。有什么想法或建议吗?如果我找不到任何方法,我将添加一个面板来NumericUpDown控制并更改其背景颜色。

每次处理程序都连接到Paint我调用的事件control.Invalidate()以重新绘制它。

4

1 回答 1

4

试试这个:

public class NumericUpDownEx : NumericUpDown
{
    bool isValid = true;
    int[] validValues = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        if (!isValid)
        {
            ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
        }
    }

    protected override void OnValueChanged(System.EventArgs e)
    {
        base.OnValueChanged(e);

        isValid = validValues.Contains((int)this.Value);
        this.Invalidate();
    }
}

假设您的值是 int 类型而不是小数。您的有效性检查可能会有所不同,但这对我有用。如果新值不在定义的有效值中,它将在整个 NumbericUpDown 周围绘制一个红色边框。

诀窍是确保在调用 base.OnPaint后进行边框绘制。否则边框会被覆盖。最好从 NumericUpDown 继承而不是分配给它的绘制事件,因为重写 OnPaint 方法可以让您完全控制绘制的顺序。

于 2013-02-09T00:07:25.767 回答