DateTimePicker UserControl 上的动态文本颜色 - WinForms

Red*_*ter 5 c# user-controls datetimepicker winforms

我正在创建一个基于 DateTimePicker 的 Windows 用户控件。该控件设置为仅显示时间,因此显示如下:

仅 DateTimePicker 时间

我有一个公共属性 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)

哪个有效,有点,但会导致一些令人震惊的结果,即

  • 即使控件被选中,它也不会显示为选中状态。
  • 单击上/下控件会更改控件的基础值,但并不总是更改可见值。
  • 通过另一个控件更改其值时,控件无法正确重绘,但将鼠标移到控件上似乎会强制重绘。

例如,看看这个奇怪的东西......

部分重绘控件

我错过了什么?

Lar*_*ech 3

尝试继承它是一个糟糕的控件,但可以尝试一些事情:

添加双缓冲区:

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)

  • 最优秀 - 非常感谢。我现在遇到的唯一问题是您无法确定选择的是小时还是分钟。当您选择控件时,两者都会突出显示。 (2认同)