我的应用程序中有一个用户表单。某些字段已验证。如果字段的值错误,则会为此控件绘制红色边框。它是通过处理该控件的Paint
事件来实现的。我扩展了 TextField
和 DateTimePicker
以从这些类对象中获取 Paint
事件。我对 NumericUpDown
类有问题。它确实正确触发 Paint
事件,但调用
ControlPaint.DrawBorder(e.Graphics, eClipRectangle, Color.Red, ButtonBorderStyle.Solid);
完全没有做任何事情。有什么想法或建议吗?如果我找不到任何方法来做到这一点,我将添加一个面板来保存 NumericUpDown
控件,并且我将更改其背景颜色。
每次处理程序连接到 Paint
事件时,我都会调用 control.Invalidate()
来重新绘制它。
最佳答案
试试这个:
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 方法可以让您完全控制绘制顺序。
关于c# - 为 NumericUpDown 绘制边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14725328/