在Windows窗体中指定位置属性时,按钮不显示

本文关键字:按钮 显示 属性 位置 窗体 Windows 定位 | 更新日期: 2023-09-27 18:13:54

我正在尝试动态添加面板内的面板依赖于列表中的人数使用以下代码时,表单加载:

private void Form1_Load(object sender, EventArgs e)
{
    const int xConst = 2;
    var people = new List<string>
    {
        "Person1",
        "Person2",
        "Person3",
        "Person4",
    };
    var y = 2;
    for (var x = 0; x < people.Count; x++)
    {
        var newpan = new MyPanel
        {
            BorderStyle = BorderStyle.None,
            Height = 25,
            Width = panel1.Width - 5,
            Location = new Point(xConst, y)
        };
        var newlbl = new Label
        {
            BorderStyle = BorderStyle.None,
            AutoSize = false,
            Text = people[x],
            Font = new Font("Segoe UI", 9.5F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(0))),
            Size = new Size(75,20),
            Location = new Point(newpan.Location.X + 2, newpan.Location.Y + 2),
        };
        var newbtn = new Button
        {
            FlatStyle = FlatStyle.Flat,
            FlatAppearance = { BorderSize = 0 },
            UseVisualStyleBackColor = true,
            Text = @"+",
            Size = new Size(15,21),
            Location = new Point(newpan.Width - 20,newpan.Location.Y - 1),
            Font = new Font("Segoe UI", 9.0F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)))
        };
        newpan.Controls.Add(newlbl);
        newpan.Controls.Add(newbtn);
        panel1.Controls.Add(newpan);
        y += 27;
    }
}

问题是,如果我在按钮和标签中都指定了Location属性,那么对于Person1迭代,只有标签和按钮的第一次迭代出现。但如果我不带Location属性,它们都会显示出来。这样做的问题是,我有一个自定义面板,它覆盖了一些东西,允许我在面板周围放置客户边框和颜色,如果我没有指定位置,标签和按钮就不会正确地定位在面板上,所以它覆盖了我的边框,看起来很邋遢。

谁能帮我弄清楚为什么会发生这种情况?我已经完成了整个程序,并观察了所有我能想到的值在观察窗口中相应增加。所有的面板都正确显示,所以我不明白为什么当我指定位置时,它们各自的标签和按钮没有显示。

在Windows窗体中指定位置属性时,按钮不显示

查看您的代码,我注意到您正在将新pan高度设置为25,并且它的位置在每次迭代中偏移27。您还使用

 'Location = new Point(newpan.Location.X + 2, newpan.Location.Y + 2)

设置按钮和标签在新面板中的位置。newpan。位置在你的panel1的坐标中被引用,你的按钮和标签的位置在你的newpan面板的坐标中被引用,因此在你的For语句的第一次迭代之后,你的标签和按钮的y位置值是29,这大于你的newpan面板的高度,使它无法被看到,在那之后的下一次迭代将是y将是56等等。每个内容控件,在本例中,您的面板将有自己的坐标系统,最简单的修复方法是这样做:

'Location = new Point( 2, 2) //for your label
'Location = new Point(newpan.Width - 20, - 1) //for your button

另一种选择是像jmcilhinney建议的那样,用你的按钮和标签已经在位置上做一个UserControl,然后你会创建它的单独实例,并将它分配给你的panel1。