【发布时间】: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