我有一个带有图片的Windows表单,一个包含错误消息的标签和一个“关闭”按钮:
错误消息可能非常短或很长,具体取决于错误。当它很长时,我希望窗口高度增长以显示整个消息。使用标签的Anchor
和MaximumSize
属性以及表单的AutoSize
属性,我可以让Label扩展到最大宽度,然后垂直展开,直到显示消息。将按钮的Anchor
属性设置为Bottom, Right
会将按钮锁定到预期的右下角,但表单只会扩展到足以显示标签,而且按钮也不够。因此按钮显示在标签后面,无法看到:
我想知道如何拉伸表单以完全包含标签的文本,并仍然在底部留出空间,以便锚定按钮生成如下内容:
答案 0 :(得分:0)
将3个面板添加到左侧,底部和填充对接的表单中。设置属性,如下图所示。
然后在属性中将Label的最大宽度设置为固定值,或者您可以在运行时计算它:
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Me.Label1.MaximumSize = New Size(Me.panelFill.Width, 0)
End Sub
答案 1 :(得分:0)
最简单的方法是使用3个停靠面板构建布局,这样(希望您可以根据需要进行调整):
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Samples
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form = new Form { Padding = new Padding(8), AutoSizeMode = AutoSizeMode.GrowAndShrink, AutoSize = true, Font = new Font("Consolas", 9, FontStyle.Bold) };
var contentPanel = new Panel { Dock = DockStyle.Fill, Parent = form, AutoSizeMode = AutoSizeMode.GrowAndShrink, AutoSize = true };
var imagePanel = new Panel { Dock = DockStyle.Left, Parent = form };
var buttonPanel = new Panel { Dock = DockStyle.Bottom, Parent = form };
var image = new PictureBox { BackColor = Color.Red, Width = 32, Height = 32, Parent = imagePanel };
imagePanel.Width = image.Width + 8;
var button = new Button { Top = 8, AutoSize = true, BackColor = Color.Green, ForeColor = Color.White, Text = "Test", Parent = buttonPanel };
button.Left = buttonPanel.DisplayRectangle.Right - button.Width;
buttonPanel.Height = button.Height + 8;
button.Anchor = AnchorStyles.Right | AnchorStyles.Bottom;
var label = new Label { Dock = DockStyle.Fill, BackColor = Color.Blue, ForeColor = Color.White, MaximumSize = new Size(300, 0), AutoSize = true, Parent = contentPanel };
label.Text = @"The error message could be very short or very long depending on what the error is. When it's long, I want the window to grow in height to display the whole message. Using the label's Anchor and MaximumSize properties and the form's AutoSize property, I was able to get the Label to expand to the maximum width and then expand vertically until the message is displayed. Setting the button's Anchor property to Bottom, Right locks the button to the bottom right corner as intended but the form only expands far enough to display the label and not enough for the button too. So the button is displayed behind the label and can't be seen:";
Application.Run(form);
}
}
}
结果: