WinForms:右对齐标签自动调整大小

发布于 2024-09-29 03:02:54 字数 389 浏览 11 评论 0原文

现在我澄清这可能是一个重复的问题:WinForms 中的右对齐标签 但没有一个答案令我满意。

问题很简单:

我有一个右对齐的标签,并将自动大小设置为 true。预期的行为是,当文本增加时,右坐标保持不变。但事实并非如此。左边的坐标是保持不变的。

我的应用程序有点小,所以我不想开始将控件放入面板等。所以我尝试了所有仅涉及标签属性的解决方案。唯一有效的方法是将 autosize 设置为 false 并放大它。 (已接受问题 N°1692383 的解决方案)。但实在是太丑了!我真的很想避免这种情况。

还有其他可能的解决方案吗?

Right now I clarify this may be a duplicated question from: Right-aligned labels in WinForms
But non of the answers satisfied me.

The problem is very simple:

I have a right aligned label with autosize set to true. The expected behavior is that when the text is increased the right coordinate remain unchanged. But that is not what it happens. The left coordinate is the one which remains unchanged.

My app is kind of small, so I don't want to start putting controls into panels and so. So I've tried all solutions that involved ONLY label properties. The only one which worked is to set autosize to false and over-size it. (Accepted solution of question Nº1692383). But it is really ugly! I'd really like to avoid that.

Any other possible solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫性小仙女 2024-10-06 03:02:54

一种解决方案是在表单构造函数中捕获标签的右边距,并在标签 SizeChanged 事件中,根据初始右边距、标签的当前 Width 重置位置以及标签 Parent 的当前宽度

这还假设标签固定在右侧以处理表单大小调整。

private readonly int _rightMargin;

public Form1()
{
    InitializeComponent();

    _rightMargin = label1.Parent.Width - label1.Right;
}

private void label1_SizeChanged(object sender, EventArgs e)
{
    label1.Location = new Point(label1.Parent.Width - _rightMargin - label1.Width, label1.Top);
}

One solution would be to capture the label's right margin in the form constructor, and in the label SizeChanged event, reset the location based on the initial right margin, the label's current Width and the label Parent's current Width.

This also assumes the label is anchored on the right to handle form resizing.

private readonly int _rightMargin;

public Form1()
{
    InitializeComponent();

    _rightMargin = label1.Parent.Width - label1.Right;
}

private void label1_SizeChanged(object sender, EventArgs e)
{
    label1.Location = new Point(label1.Parent.Width - _rightMargin - label1.Width, label1.Top);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文