Skip to main content
 首页 » 编程设计

c#之以编程方式添加到 FlowLayoutPanel 的项目不像设计时那样对齐

2024年02月05日16bonelee

这是编程插入之前的面板:

之后:

我添加了其他从 Review 标签样式复制的行,希望这是一个填充或边距问题。不幸的是,情况似乎并非如此。澄清一下,FlowLayoutPanel 本身向右延伸了一个很好的距离,超出了新标签应该需要的距离,如下所示:

所有其他 Label是 AutoSize启用。

下面是生成和插入的代码:

Label newLabel = new Label(); 
newLabel.Name = optionString; 
newLabel.Text = type; 
newLabel.Font = ReviewLabel.Font; // just a random label. only thing that matters is consistent styling. 
newLabel.ForeColor = ReviewLabel.ForeColor; 
newLabel.Margin = ReviewLabel.Margin; 
newLabel.Padding = ReviewLabel.Padding; 
 
LabelsPanel.Controls.Add(typeLabel); 

optionString是type删除空格。 type的值是“服务条款”。感谢您的帮助。

编辑:这里说明了如果我定义一个 Label 会有多少空间。在设计时只需拖动 Label从控制面板到表单并设置 Size和 Text属性。

请您参考如下方法:

请参阅 Label.AutoSize() 中的注释:

When added to a form using the designer, the default value is true. When instantiated from code, the default value is false.

所以你可能需要添加:

newLabel.AutoSize = true;