【问题标题】:Draw border for NumericUpDown为 NumericUpDown 绘制边框
【发布时间】:2013-02-06 09:15:52
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你解决了吗?

标签: c# winforms .net-4.0


【解决方案1】:

试试这个:

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 类型而不是 decimal。您的有效性检查可能会有所不同,但这对我有用。如果新值不在定义的有效值中,它会在整个 NumbericUpDown 周围绘制一个红色边框。

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

【讨论】:

  • 我试图在不扩展 NumericUpDown 类的情况下实现它。谢谢你的帮助。我的扩展类不包含验证方法以使其更灵活。我在 setter 中使用 Invalidate() 调用添加了颜色和边框样式的属性。其实我可以让delegate和它的实例字段让所有者添加验证器到这个控件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-19
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
相关资源
最近更新 更多