Ele*_*iac 3 c# label width winforms
我正在使用代码编辑器,并希望随着数字的增加自动调整标签的宽度。例如,对于 1-9(1 位数字),有一个特定的宽度。然后当它达到 10-99(2 位数)时,标签的宽度增加。然后又是 100-999(3 位数)等。
结果应该是这样的:

这是我的代码:
private void timer_countline_Tick(object sender, EventArgs e)
{
updateNumberLabel();
}
private void updateNumberLabel()
{
// we get index of first visible char and number of first visible line
Point pos = new Point(0, 0);
int firstIndex = rtb.GetCharIndexFromPosition(pos);
int firstLine = rtb.GetLineFromCharIndex(firstIndex);
// now we get index of last visible char and number of last visible line
pos.X = ClientRectangle.Width;
pos.Y = ClientRectangle.Height;
int lastIndex = rtb.GetCharIndexFromPosition(pos);
int lastLine = rtb.GetLineFromCharIndex(lastIndex);
// this is point position of last visible char, we'll use its Y value for calculating numberLabel size
pos = rtb.GetPositionFromCharIndex(lastIndex);
// finally, renumber label
numberLabel.Text = "";
for (int i = firstLine; i <= lastLine + 1; i++)
numberLabel.Text += i + 1 + "\n";
}
Run Code Online (Sandbox Code Playgroud)
您可以使用TextRenderer做您想做的事。请检查以下代码行(您应该将代码行添加到标签的TextChanged事件中):
请记住,您的控件的AutoSize属性必须设置为False。
这是改变宽度的控制,以适应其内容的宽度。
yourLabelName.Width = TextRenderer.MeasureText(yourLabelName.Text, yourLabelName.Font).Width;
Run Code Online (Sandbox Code Playgroud)
这是改变高度的控制,以适应其内容的高度。
yourLabelName.Height = TextRenderer.MeasureText(yourLabelName.Text, yourLabelName.Font).Height;
Run Code Online (Sandbox Code Playgroud)
要更改面板宽度以水平显示其中的所有内容,您可以使用以下代码行:
yourPanelName.Width = yourLabelName.Left + yourLabelName.Width;
Run Code Online (Sandbox Code Playgroud)
要更改面板高度以显示其中的所有内容,您可以使用以下代码行:
yourPanelName.Height = yourLabelName.Top + yourLabelName.Height;
Run Code Online (Sandbox Code Playgroud)
如果您使用SplitContainer 控件,则必须按如下方式更改您的 SplitContainer 的属性:
FixedPanel = none
IsSplitterFixed = False
Run Code Online (Sandbox Code Playgroud)
然后您可以使用以下代码行来实现您想要的:
要更改SplitContainer 面板宽度以水平显示其中的所有内容,您可以使用以下代码行:
int yourLabelNameWidth = TextRenderer.MeasureText(yourLabelName.Text, yourLabelName.Font).Width;
yourSplitContainerName.SplitterDistance = yourLabelName.Left + yourLabelNameWidth;
yourLabelName.Width = yourLabelName.Left + yourLabelNameWidth;
Run Code Online (Sandbox Code Playgroud)