Home > Software design >  Limit on number of lines, both wrapped and line breaks
Limit on number of lines, both wrapped and line breaks

Time:09-17

I have a requirement to count the number of lines in a UWP TextBox. This is to enforce a maximum number of lines that are allowed in the TextBox. In theory it seems very straight-forward, but in practise it doesn't seem all that clear.

The requirement is a textbox that does not scroll horizontally or vertically. When it would reach the width limit, it wraps - and also, when it reaches the maximum number of lines it should not scroll vertically and should instead disable any further input. The user can also press the return key to add in any new lines they want, but not above the maximum number of lines.

I don't think there is a combination of xaml properties I can set on the TextBox to achieve this, so I assume it has to be in a text changed event. So in order to enforce a limit on the number of lines, I must count them. I have attempted it with this:

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

However this only returns line breaks that are manually entered by the user - not wrapped lines! Wrapped line-breaks don't seem to appear as any ascii character in the Text property at all, so detecting them is tough.

My question is: How can I enforce a limit on the number of lines in a TextBox control, taking into account both wrapped lines and line breaks?

CodePudding user response:

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

TextBox contains GetRectFromCharacterIndex method that you could used to get specific character's rect. And the rect has line height and bottom value, you could calculate current line number with bottom/line height.

The following is TextBox line number of last character calculating steps.

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