2

我有一些文本框只允许包含一定数量的字符,例如在大多数情况下为 12 或 14。

是否可以根据单词将文本框动态调整为 12 个字符或 14 个字符的宽度?

4

2 回答 2

0

I am not quite sure if i understand your question right, but for a given string you might set the Text and Width property of a TextBox simultaneously like the sample method below.

It creates a FormattedText object from the given text and all the font-related properties of the TextBox. Then it assigns an empty string to the TextBox to get the "empty" width (which should also be possible by adding left and right padding, left and right border thickness etc). Finally the method assigns the Text property and sets the Width to the empy width plus the width of the FormattedText.

public void SetTextAndWidth(TextBox textBox, string text)
{
    Typeface typeface = new Typeface(
        textBox.FontFamily, textBox.FontStyle, textBox.FontWeight, textBox.FontStretch);

    FormattedText formattedText = new FormattedText(text, CultureInfo.InvariantCulture,
        FlowDirection.LeftToRight, typeface, textBox.FontSize, Brushes.Black);

    if (textBox.HorizontalAlignment == HorizontalAlignment.Stretch)
    {
        textBox.HorizontalAlignment = HorizontalAlignment.Left;
    }

    textBox.Text = "";
    double emptyWidth = textBox.ActualWidth;

    textBox.Text = text;
    textBox.Width = formattedText.Width + emptyWidth;
}
于 2012-08-27T09:51:10.170 回答
0

总是有TextRenderer.MeasureText方法。

只要您不介意使用表单 DLL。

或图形库辅助方法Graphics.MeasureString

然后,您可以使用此信息进行各种尺寸调整,查看 MSDN 条目中的示例。

于 2012-08-28T08:47:59.130 回答