0

我已经在交流表单上动态添加了复选框......
并且在加载表单时它们被禁用......
默认情况下每个复选框都有红色......我以编程方式将其分配为黑色......
但是当表单被加载时它是红色的……我不知道为什么会这样……

private void Form2_Load(object sender, EventArgs e)
{
    for (int i = 0; i < list.Count; i++)
    {
         CheckBox c = new CheckBox();
         c.Text = i.ToString();
         c.Width = 120;
         flowLayoutPanel1.Controls.Add(c);
         c.ForeColor = Color.Black;
    }
    flowLayoutPanel1.Enabled = false;
}

只有在我启用 flowLayoutPanel 后它才会变成黑色......
我希望复选框即使在加载表单时也有黑色......

4

2 回答 2

2

这是一种方法。将您的代码更改为:

for (int i = 0; i < list.Count; i++)
{
    CheckBox c = new CheckBox();
    c.Text = "";
    c.Tag = i.ToString();
    c.Width = 120;
    flowLayoutPanel1.Controls.Add(c);
    c.Paint += new PaintEventHandler(c_Paint);

}
    flowLayoutPanel1.Enabled = false;

在 c_Paint 方法中,您可以绘制控件的文本(保存在 Tag 属性中)

void c_Paint(object sender, PaintEventArgs e)
{
    Control c = sender as Control;
    if (c != null)
    {
        string text = c.Tag.ToString();
        e.Graphics.SmoothingMode = 
            System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        RectangleF rect = new RectangleF(
            new PointF(19, 5), 
            e.Graphics.DrawString(text, this.Font, Brushes.Black, new PointF(19, 5));
    }
}
于 2012-05-09T10:55:47.780 回答
0

您应该创建一个函数来执行此操作并InitializeComponent();在表单构造函数中调用它。您也应该先启用面板。

public partial class YourForm: Form
    {
        public YourForm()
        {
            InitializeComponent();
           // put your function here
        }
于 2012-05-09T10:13:03.967 回答