【问题标题】:TextBox.Text Doesn't Right JustifyTextBox.Text 不能右对齐
【发布时间】:2012-04-10 09:00:19
【问题描述】:

根据我的理解,如果文本比文本框显示的长,下面的代码应该右对齐文本,否则保持左对齐。

问题在于它实际上并没有这样做,而且表现得很奇怪。短字符串有时会右对齐,而长字符串总是左对齐。

我做错了什么?

private void textBoxCurrentConfig_TextChanged(object sender, EventArgs e)
{
    SizeF stringSize = new SizeF();
    stringSize = TextRenderer.MeasureText(textBoxCurrentConfig.Text, textBoxCurrentConfig.Font);

    float currentTextWidth = stringSize.Width;
    float allowedTextWidth = textBoxCurrentConfig.Size.Width - 10;

    if (currentTextWidth >= allowedTextWidth) // if the text we want to display is larger than the textbox can hold, right justify it to show the filename
    {
        textBoxCurrentConfig.TextAlign = HorizontalAlignment.Right; // right justify                
    }
    else // otherwise we can display the entire path
    {
        textBoxCurrentConfig.TextAlign = HorizontalAlignment.Left; // left justify
    }

    textBoxCurrentConfig.Refresh();
    this.Refresh();
}

【问题讨论】:

  • current... 和 allowed... 的数字是多少?调试的时候有用吗?
  • 我通过逐步测试代码。这些数字很有意义,逻辑也很好。让我失望的是对齐方式。
  • @Kashif 您在使用 WinForms 吗?从代码中可以看出,您根据文本长度设置了光标位置。如果是这种情况,那么您可以使用 textBoxCurrentConfig.Select() 方法。
  • 是的,我正在使用 WinForms。我已经按照您的建议尝试了“textBoxCurrentConfig.Select()”,但它似乎没有将光标位置移动到任何一侧。选择控件后可能还有一个额外的步骤?
  • @Kashif 很简单,使用 textBoxCurrentConfig.Select(0, 0);和 textBoxCurrentConfig.Select(textBoxCurrentConfig.Text.Length, 0);在开头或结尾移动光标。详情请查看MSDNmsdn.microsoft.com/en-us/library/…

标签: c# string textbox text-justify


【解决方案1】:

从您的 cmets 开始,您希望根据文本长度移动光标位置。您可以为此使用TextBox.Select() 方法。 Check MSDN for details.

所以如果你想在文本的开头移动光标,你可以使用

textBoxCurrentConfig.Select(0, 0);

如果你想在文本末尾移动光标,你可以使用

textBoxCurrentConfig.Select(textBoxCurrentConfig.Text.Length, 0);

【讨论】:

    【解决方案2】:

    尝试删除

    this.Refresh();
    

    可能会导致页面刷新,文本框恢复原来的对齐方式

    【讨论】:

    • 我尝试了 this.Refresh(); 的所有组合和 textBoxCurrentConfig.Refresh();没有运气=/
    • 您需要多解释一下。恐怕我对 css 不了解
    • 很难用一行来解释它,但我尝试:它定义了页面的设计。所以你可能有一个定义来定义右边的文本并覆盖你的样式设计
    • 我会环顾四周,看看是否能理解 css。谢谢
    • 检查此链接,它可能会有所帮助:text-align, direction
    猜你喜欢
    • 1970-01-01
    • 2012-06-10
    • 2013-07-23
    • 2020-01-25
    • 2019-05-09
    • 2011-11-05
    • 2015-08-24
    • 2013-06-17
    • 1970-01-01
    相关资源
    最近更新 更多