Red*_*ter 5 c# user-controls datetimepicker winforms
我正在创建一个基于 DateTimePicker 的 Windows 用户控件。该控件设置为仅显示时间,因此显示如下:

我有一个公共属性 TimeIsValid:
public bool TimeIsValid
{
get { return _timeIsValid; }
set
{
_timeIsValid = value;
Refresh();
}
}
Run Code Online (Sandbox Code Playgroud)
当它设置为 false 时,我希望文本变成红色。所以我用以下代码覆盖了 OnPaint:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawString(Text, Font,
_timeIsValid ? new SolidBrush(Color.Black) : new SolidBrush(Color.Red),
ClientRectangle);
}
Run Code Online (Sandbox Code Playgroud)
这没有任何作用。所以在构造函数中我添加了以下代码:
public DateTimePicker(IContainer container)
{
container.Add(this);
InitializeComponent();
//code below added
this.SetStyle(ControlStyles.UserPaint, true);
}
Run Code Online (Sandbox Code Playgroud)
哪个有效,有点,但会导致一些令人震惊的结果,即
例如,看看这个奇怪的东西......
我错过了什么?
尝试继承它是一个糟糕的控件,但可以尝试一些事情:
添加双缓冲区:
this.SetStyle(ControlStyles.UserPaint |
ControlStyles.OptimizedDoubleBuffer, true);
Run Code Online (Sandbox Code Playgroud)
如果控件具有焦点,则清除背景并绘制突出显示:
protected override void OnPaint(PaintEventArgs e) {
e.Graphics.Clear(Color.White);
Color textColor = Color.Red;
if (this.Focused) {
textColor = SystemColors.HighlightText;
e.Graphics.FillRectangle(SystemBrushes.Highlight,
new Rectangle(4, 4, this.ClientSize.Width - SystemInformation.VerticalScrollBarWidth - 8, this.ClientSize.Height - 8));
}
TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, textColor, Color.Empty, TextFormatFlags.VerticalCenter);
base.OnPaint(e);
}
Run Code Online (Sandbox Code Playgroud)
并在值更改时使控件无效:
protected override void OnValueChanged(EventArgs eventargs) {
base.OnValueChanged(eventargs);
this.Invalidate();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2190 次 |
| 最近记录: |