我正在使用用户控件来显示两个日期之间的时间。我的问题是当应用程序开始运行或每次刷新()时,用户控件的所有图形都会消失,直到调整窗体大小。
观察表单在刷新时的行为方式,用户控件在屏幕上显示几帧后才会消失。
我希望你能帮助我解决这个谜团,因为我对这个问题一无所知。
最诚挚的问候, 的Mathias
PS:这是我的用户控件代码:
public partial class CalendarView : UserControl
{
[Category("Behavior")]
//these reads the start and end date for the datastrip from the parent form
public DateTime StartDateTime (...)
public DateTime EndDateTime (...)
public int Space
{
get
{
double totalDays = (EndDateTime - StartDateTime).TotalDays;
if (totalDays == 0) { totalDays = 1; }
return (int)(GraphicsWidth / totalDays);
}
}
private int GraphicsWidth
{
get
{
return panelDateTimeStrip.Width - 2;
}
}
public CalendarView()
{
InitializeComponent();
}
private void drawDates()
{
Pen darkGray = new Pen(SystemColors.ControlDarkDark);
Pen lightGray = new Pen(Color.LightGray);
Pen gray = new Pen(Color.Gray);
SolidBrush brush = new SolidBrush(SystemColors.ControlDarkDark);
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
int graphicsHeight = panelDateTimeStrip.Height - 2;
Graphics graphics = panelDateTimeStrip.CreateGraphics();
//<-----drawing all graphics------>\\
graphics.Dispose();
darkGray.Dispose();
lightGray.Dispose();
gray.Dispose();
}
protected override void OnPaint(PaintEventArgs e)
{
drawDates();
base.OnPaint(e);
}
private void CalendarView_Resize(object sender, EventArgs e)
{
Invalidate();
}
private void CalendarView_Load(object sender, EventArgs e)
{
drawDates();
}
}
答案 0 :(得分:0)
这些评论几乎可以回答这个问题,但由于还没有人发布答案,以下是您应该如何更改代码:
private void drawDates(Graphics graphics)
{
// create pens and brushes
// do not CreateGraphics, use the parameter instead
//<-----drawing all graphics------>\\
// dispose pens and brushes; do not dispose graphics!
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
drawDates(e.Graphics);
}
请注意,在进行自己的绘图之前,请先致电base.OnPaint
,并且不再使用CreateGraphics
。