行数限制,包括换行和换行

Limit on number of lines, both wrapped and line breaks

我需要计算 UWP 中的行数 TextBox。这是为了强制执行 TextBox 中允许的最大行数。理论上看起来很简单,但在实践中似乎并不那么清楚。

要求是不能水平或垂直滚动​​的文本框。当它达到宽度限制时,它会换行 - 而且,当它达到最大行数时,它应该 而不是 垂直滚动并且应该禁用任何进一步的输入。用户还可以按 return 键添加他们想要的任何新行,但不能超过最大行数。

我不认为我可以在 TextBox 上设置 xaml 属性的组合来实现此目的,因此我假设它必须在文本更改事件中。因此,为了对行数施加限制,我必须对它们进行计数。我试过这个:

int numLines = txtBox.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None).Length;
if (numLines > maxLines)
{
    // reject edit
}

然而,这只是用户手动输入的 returns 换行符 - 不是换行!换行符似乎根本不会在 Text 属性 中显示为任何 ascii 字符,因此很难检测到它们。

我的问题是:如何在考虑换行和换行的情况下,对TextBox控件中的行数实施限制?

However this only returns line breaks that are manually entered by the user - not wrapped lines!

TextBox 包含 GetRectFromCharacterIndex 方法,您可以使用该方法获取特定字符的矩形。并且矩形有行高和底值,你可以用bottom/line高度计算当前行号。

以下是TextBox最后一个字符计算步骤的行号

var specificRect = MyTextBox.GetRectFromCharacterIndex(MyTextBox.Text.Length-1, true);
var lineNumber = Math.Round(specificRect.Bottom / specificRect.Height);
System.Diagnostics.Debug.WriteLine("Line Number:" + lineNumber);