I am creating a windows user control based on a DateTimePicker. The control is set to show just the time so it displays thus:
I have a public property TimeIsValid:
public bool TimeIsValid
{
get { return _timeIsValid; }
set
{
_timeIsValid = value;
Refresh();
}
}
and when this is set to false I want the text to turn red. So I have overridden the 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);
}
This did nothing. So in the in the constructor I have added the following code:
public DateTimePicker(IContainer container)
{
container.Add(this);
InitializeComponent();
//code below added
this.SetStyle(ControlStyles.UserPaint, true);
}
Which works, kind of, but causes some alarming results i.e.
Look at this weirdness for instance ...
What am I missing?
It's a lousy control to try to inherit from, but some things to try:
Add the double-buffer:
this.SetStyle(ControlStyles.UserPaint |
ControlStyles.OptimizedDoubleBuffer, true);
Clear the background and draw the highlight if the control has the focus:
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);
}
and invalidate the control when the value changes:
protected override void OnValueChanged(EventArgs eventargs) {
base.OnValueChanged(eventargs);
this.Invalidate();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With