C# 如何按下控制按钮
我有一个带有可变长度文本的标签,下面有一个进度条。我想在标签和progressBar之间留一个空间,因此根据标签的文本(已包装),progressBar应该向下推,始终保持它们之间的空间。我该怎么做?我尝试了C# 如何按下控制按钮,c#,winforms,label,vertical-alignment,C#,Winforms,Label,Vertical Alignment,我有一个带有可变长度文本的标签,下面有一个进度条。我想在标签和progressBar之间留一个空间,因此根据标签的文本(已包装),progressBar应该向下推,始终保持它们之间的空间。我该怎么做?我尝试了AutoSize=true和AutoSizeMode=growthandshrink,但没有改变任何事情。例如: --------------------------- | for example the label's | | text might be something |
AutoSize=true
和AutoSizeMode=growthandshrink
,但没有改变任何事情。例如:
---------------------------
| for example the label's |
| text might be something |
| like this, with a lot of |
| of text but the progress |
| bar should be here |
| |
| progressBar here |
---------------------------
例2:
---------------------------
| small text |
| |
| progressBar here |
---------------------------
设置label.text。然后
progessBar.Top = label.Bottom + WhateverSpaceYouWant
如果保存progressbar的初始
Y
位置,以后可以根据标签的高度动态设置位置。它将保留您最初设置的填充
因此,如果我有以下表单,其中标签在按下按钮时自动更新,我可以在按钮单击事件中更新进度条位置
public partial class Form1 : Form
{
private readonly int initialProgressbarLocationY;
public Form1()
{
InitializeComponent();
label1.MaximumSize = new Size(80, 1000); //Wrapping label
label1.AutoSize = true;
initialProgressbarLocationY = progressBar1.Location.Y; //Save the original position
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text += "bla blablablabla bla";
MoveProgressbar();
}
private void MoveProgressbar()
{
// Set the progressbar at the same X, but update the Y according to the label's height
progressBar1.Location = new Point(progressBar1.Location.X,
initialProgressbarLocationY + label1.Height);
}
}
点击几次按钮后会得到以下结果:
如果标签以某些文本开头,则可能需要从新的Y减去原始标签高度,否则第一次填充将略微增加。将标签和进度条放入一个其
流动方向
属性设置为自上而下
。现在,当标签垂直增长时,ProgressBar将自动向下推。要控制标签和进度条之间的距离,请更改标签的Padding
属性中的Bottom
值
以下是在表单和FlowLayoutPanel(使用AutoSizeMode
中的GrowtOnly
)中将AutoSizeMode设置为true
点击几次按钮后,我的表单的外观:
公共部分类表单1:表单
{
公共表格1()
{
初始化组件();
}
私有无效按钮1\u单击(对象发送者,事件参数e)
{
对于(int i=1;i<20;i++)
{
label1.Text=label1.Text+“更多”;
}
}
}
Awesome,不知道Winforms有一个FlowLayoutPanel。我无法在这里复制它。这是我的表单,点击两次按钮后,我的表单如下所示:FlowDirection=top-down
和表单的AutoSize=true
。我缺少什么?也是GrowOnly=AutoSizeMode
,但这是默认值。@Jack您需要在FlowLayoutPanel和FormI上都将AutoSize设置为true。我正在尝试再次实现此功能。但是文本没有正确增长。。。我该如何解决这个问题?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for(int i = 1 ; i < 20; i++)
{
label1.Text = label1.Text + " more ";
}
}
}