为NumericUpDown绘制边框 [英] Draw border for NumericUpDown

查看:55
本文介绍了为NumericUpDown绘制边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an user form in application. Some fields are validated. If field has wrong value red border is drawn for this control. It is made by handling Paint event for this control. I extended TextField and DateTimePicker to get Paint event from those classes objects. I have problem with NumericUpDown class. It does fire Paint event properly but invoking

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

完全不执行任何操作.有什么想法或建议吗?如果找不到任何方法,我将添加一个面板来保存 NumericUpDown 控件,然后将其背景色更改.

does completely nothing. Any ideas or suggestions? If I won't find any way to do it, I will add a panel to hold NumericUpDown control and I will be changing its background colour.

每个时间处理程序都与 Paint 事件相关,我调用 control.Invalidate()进行重绘.

Each time handler is hooked up to Paint event I call control.Invalidate() to get it repainted.

推荐答案

尝试一下:

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周围绘制一个红色边框.

Assuming your values are type int and not decimal. Your validity checking will probably be different but this worked for me. It draws a red border around the entire NumbericUpDown if the new value is not in the defined valid values.

诀窍是确保在调用base.OnPaint之后在 之后进行边框绘制.否则,边框将被绘制.从NumericUpDown继承而不是分配其paint事件可能更好,因为重写OnPaint方法可以完全控制绘画顺序.

The trick is to make sure you do the border painting after calling base.OnPaint. Otherwise the border will get drawn over. It may be better to inherit from NumericUpDown rather than assigning to its paint event because overriding the OnPaint method gives you complete control on the order of painting.

这篇关于为NumericUpDown绘制边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆