2013-02-06 82 views
1

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

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

完全没有。任何想法或建议?如果我找不到任何方法来执行此操作,我将添加一个控制面板来控制NumericUpDown控件,并且我将更改其背景颜色。

每个时间处理程序都连接到Paint事件,我呼叫control.Invalidate()重新绘制它。

+0

你解决了吗? – sparky68967

回答

3

试试这个:

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方法可以完全控制绘画的顺序。

+0

我试图在不扩展'NumericUpDown'类的情况下实现它。谢谢你的帮助。我的扩展类不包含验证方法,使其更加灵活。我通过setter中的Invalidate()调用了颜色和边框样式的属性。 其实我可以让委托和它的实例字段让所有者添加验证器到这个控件。 – Eloar