Draw border for NumericUpDown

妖精的绣舞 提交于 2021-02-19 06:13:36

问题


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);

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.

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


回答1:


Try this:

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();
    }
}

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.

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.



来源:https://stackoverflow.com/questions/14725328/draw-border-for-numericupdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!