2015-10-26 122 views
0

我有一个Windows窗体与图像,包含错误消息的标签,而“关闭”按钮:保持锚下面的按钮自动调整大小标签

Before

的错误信息可能是非常短或取决于错误是什么。当它很长时,我希望窗口高度增长以显示整个消息。使用标签的AnchorMaximumSize属性和表单的AutoSize属性,我可以使标签展开到最大宽度,然后垂直展开直到显示消息。将该按钮的Anchor属性设置为Bottom, Right可将按钮锁定到右下角,但表单只能展开足够多,才能显示标签,而对于按钮来说也不够。所以按钮显示在标签后面,不能看到:

After

我想知道我怎么能伸展的形式完全包含标签的文本,并仍处于留有余地底部锚定的按钮来产生这样的:

Desired

+1

TableLayoutPanel是为此设计的 – Plutonix

回答

0

添加3个面板的形式定位在左,底部和填充。按照下图所示设置属性。

然后在属性标签的最大宽度设定为固定值,或者可以在运行时计算它:

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 

example form

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); 
     } 
    } 
} 

结果:

enter image description here