Dynamic Text Color on DateTimePicker UserControl - WinForms

I am creating a Windows user control based on DateTimePicker. The control is set to show only the time so that it is displayed in this way:

DateTimePicker time only

I have a public TimeIsValid property:

public bool TimeIsValid
{
   get { return _timeIsValid; }
   set
   {
      _timeIsValid = value;
      Refresh();
   }
}

and if this parameter is set to false, I want the text to turn red. So I redefined OnPaint with the following code:

    protected override void OnPaint(PaintEventArgs e)
     {
        base.OnPaint(e);

        e.Graphics.DrawString(Text, Font, 
        _timeIsValid ? new SolidBrush(Color.Black) : new SolidBrush(Color.Red),
        ClientRectangle);

     }

It did nothing. Therefore, in the constructor, I added the following code:

public DateTimePicker(IContainer container)
{
    container.Add(this);
    InitializeComponent();
    //code below added
    this.SetStyle(ControlStyles.UserPaint, true);
}

Which works, it seems, but causes some disturbing results, i.e.

  • The control is not displayed, even if it is.
  • Pressing the up / down buttons changes the base value of the control, but does not always change the visible value.
  • , , -, .

, ...

Partially repainted control

?

+4
1

, , , :

:

this.SetStyle(ControlStyles.UserPaint | 
              ControlStyles.OptimizedDoubleBuffer, true);

, :

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);
}

:

protected override void OnValueChanged(EventArgs eventargs) {
  base.OnValueChanged(eventargs);
  this.Invalidate();
}
+2

All Articles