c# 动态创建的标签大小不够宽

c# dynamically created label size not wide enough

动态创建标签时,部分文本丢失。这是因为标签的尺寸不够宽,它截断了实际字符串的一部分。

我怎样才能让它停止?我不想也不记得为标签设置尺寸。它不应该继续直到字符串为空吗?

示例:value = "Berserker's Iron Axe",它只显示 "Berserker's Iron",因为我没有设置它的大小,它去掉了字符串的一部分。

    PictureBox finalResult_pBox = new PictureBox {
                                    Name = "finalResult_pBox" + i,
                                    Size = new Size(64, 64),
                                    Padding = new Padding(0),
                                    BorderStyle = BorderStyle.FixedSingle,

                                    ImageLocation = spidyApi_idByName_result.results[i].img.ToString(),
                                };
                              MessageBox.Show(spidyApi_idByName_result.results[i].name.ToString());

                                Label finalResult_itemName_label = new Label{
                                    Name = "finalResult_itemName_label" + i,
                                    Text = spidyApi_idByName_result.results[i].name,
                                };

                                FlowLayoutPanel finalResult_panel = new FlowLayoutPanel{
                                    FlowDirection = FlowDirection.TopDown,
                                    BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle,
                                    Name = "result_flowLayoutPanel" + i,
                                    Size = new System.Drawing.Size(790, 64),
                                    TabIndex = i,
                                };



finalResult_panel.Controls.Add(finalResult_pBox);
finalResult_panel.Controls.Add(finalResult_itemName_label);
result_flowLayoutPanel.Controls.Add(finalResult_panel);

为什么会发生这种情况,我该如何解决?

只要您保留 Label.AutoSize = true,这是默认设置,它就会自动调整自己的大小。

您可能想做一些测试以查看实际尺寸,例如

  • 设置一个BorderStyle
  • BackColor
  • 或者在文本中插入一个space,所以它有机会转到第二行..

  • 当然你 可以 测量文本(例如 TextRenderer.MeasureText(text, Label.Font); 但这肯定不是必要的,因为文本只是为了显示..不过,它对于要求更高的布局控制很有用。

因此,首先要确保 AutoSize 为真,或者您测量并设置了 Label..

Size