根据内容宽度调整标签宽度

3
我正在开发一个代码编辑器,希望在数字增加时自动调整标签的宽度。例如,对于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";
}

@GrantWinney,是的,问题在于每次我这样做时标签都会闪烁,因为我使用了timerevent。 - Elegiac
@Elegiac AutoSize应该可以正常工作。没有更好的方法。 - King King
@Elegiac 如果你想要创建一个订单列,我认为你应该将每个条目添加为“Label”,你的“updateNumberLabel”方法会在计时器间隔较小的情况下使标签闪烁。我的意思是你应该改变你想要显示订单列的方式。如果你想保持当前的方式,你可能需要使用“SuspendLayout()”和“ResumeLayout()”方法。 - King King
@KingKing,您能否详细解释一下?抱歉,我是新手。非常感谢您的回复。 - Elegiac
1个回答

5
你可以使用TextRenderer来实现你想要的功能。请检查以下代码行(你应该将这些代码行添加到标签的TextChanged事件中)请记住,你的控件的AutoSize属性必须设置为False 这是为了更改你的控件的Width以适应其内容的宽度。
yourLabelName.Width = TextRenderer.MeasureText(yourLabelName.Text, yourLabelName.Font).Width;

这是用于更改您的控件的高度,以适应其内容的高度。

yourLabelName.Height = TextRenderer.MeasureText(yourLabelName.Text, yourLabelName.Font).Height;

更新1:

如果你想要改变面板的宽度,以水平方式显示所有内容,你可以使用以下代码:

yourPanelName.Width = yourLabelName.Left + yourLabelName.Width;

如需更改面板 高度 以垂直显示其中所有内容,您可以使用以下代码行:

yourPanelName.Height = yourLabelName.Top + yourLabelName.Height;

更新 2:

如果您使用了 SplitContainer 控件,则必须按照以下方式更改其属性:

FixedPanel = none
IsSplitterFixed = False

那么您可以使用以下代码来实现您想要的效果:

如果要更改 SplitContainer 面板的宽度 以水平显示其所有内容,可以使用以下代码行:

int yourLabelNameWidth = TextRenderer.MeasureText(yourLabelName.Text, yourLabelName.Font).Width;
yourSplitContainerName.SplitterDistance = yourLabelName.Left + yourLabelNameWidth;
yourLabelName.Width = yourLabelName.Left + yourLabelNameWidth;

先生,我在这段代码中遇到了一个错误:splitContainer1.Panel1.Width = numberLabel.Left + numberLabel.Width; --- 不支持,无法显式设置分隔面板的宽度。请在 splitContainer 上设置 splitterDistance。 - Elegiac
如果您检查“更新2”部分中的最后几行代码,您将看到您在评论中提到的内容。 - MRS1367

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接