您好,我已经为 Windows 窗体 C# 创建了一个 userControl,我在代码中动态添加了一些面板,在运行窗体后我的控件没有出现在窗体中,我从代码中删除了添加的控件,然后控件出现可以帮助我请 ??
public partial class Schedual : UserControl
{
int days;
public int Days
{
get { return days; }
set
{
days = value;
change = true;
this.Refresh();
}
}
int periods;
public int Periods
{
get { return periods; }
set
{
periods = value;
change = true;
this.Refresh();
}
}
Brush brush;
bool change;
List<Panel> panels;
public Schedual()
{
InitializeComponent();
this.days = 1;
this.periods = 1;
brush = Brushes.White;
change = false;
panels = new List<Panel>();
InitFirstPanel();
}
/// <summary>
/// Initialize the first panel on the board
/// </summary>
private void InitFirstPanel()
{
var p = new Panel();
p.Size = this.Size;
p.Location = this.Location;
AddPanels(p);
}
/// <summary>
/// Adds a given panel to the list of panels
/// </summary>
/// <param name="panel">the wanted panel</param>
private void AddPanels(Panel panel)
{
panels.Add(panel);
this.Controls.Add(panel); //if i removed this then the control work
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("Yaser", new Font("Arial", 20.5f), Brushes.Violet, new PointF(200, 150));
base.OnPaint(e);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
Graphics g = e.Graphics;
var h = this.Height / days;
var w = this.Width / periods;
g.Clear(Color.White);
g.FillRectangle(Brushes.White, new Rectangle(0,0,this.Width,this.Height));
if (change)
panels.Clear();
for (int i = 0; i <= days; i++)
{
for (int j = 0; j <= periods; j++)
{
g.FillRectangle(brush, j * w, i * h, w, h);
if (change)
{
AddPanel(j * w, i * h, w, h);
}
g.DrawLine(Pens.Black, 0, i * h, this.Width, i * h);
g.DrawLine(Pens.Black, j * w, 0, this.Height, j * w);
if (brush == Brushes.White)
brush = Brushes.YellowGreen;
else
brush = Brushes.White;
}
}
change = false;
}
/// <summary>
/// Create a new Panel and adds it to the list
/// </summary>
/// <param name="x">the x position of the panel</param>
/// <param name="y">the y position of the panel</param>
/// <param name="width">the width of the panel</param>
/// <param name="height">the height position of the panel</param>
private void AddPanel(int x, int y, int width, int height)
{
var panel = new Panel();
panel.Location = new Point(x, y);
panel.Size = new Size(width, height);
AddPanels(panel);
}
}