Предельная длина строки в многострочном текстовом поле - PullRequest
0 голосов
/ 04 апреля 2019

Мне нужно ограничить количество символов в одной строке, которые пользователь может ввести в многострочное текстовое поле.У меня есть функция, которая может сделать это для данных, набранных, но не для данных, вырезанных и вставленных.

Я попытался прочитать текстовое поле в массив, используя подстроку и скопировать обратно в текстовую строку,но этот код (размещен) выдает исключение.

private void LongLine_TextChanged(object sender, TextChangedEventArgs e)
    {
        int lineCount = 
 ((System.Windows.Controls.TextBox)sender).LineCount;
        //string newText = "";
        for (int i = 0; i < lineCount; i++)
        {
            if 
    (((System.Windows.Controls.TextBox)sender).GetLineLength(i) > 20)
            {
                string textString = ((System.Windows.Controls.TextBox)sender).Text;
                string[] textArray = Regex.Split(textString, "\r\n");
                textString = "";
                for (int k =0; k < textArray.Length; k++)
                {
                    String textSubstring = textArray[k].Substring(0, 20);
                    textString += textSubstring;
                }
                ((System.Windows.Controls.TextBox)sender).Text = textString;
            }
        }
        e.Handled = true;
    }

1 Ответ

0 голосов
/ 04 апреля 2019

Это делает то, о чем вы, похоже, просите:

Обрезает конец любой строки длиннее 20 при вводе и вставке или изменении текста.

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    const int MAX_LINE_LENGTH = 20;
    var textbox = sender as TextBox;
    var exceedsLength = false;
    // First test if we need to modify the text
    for (int i = 0; i < textbox.LineCount; i++)
    {
        if (textbox.GetLineLength(i) > MAX_LINE_LENGTH)
        {
            exceedsLength = true;
            break;
        }
    }
    if (exceedsLength)
    {
        // Split the text into lines
        string[] oldTextArray = textbox.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
        var newTextLines = new List<string>(textbox.LineCount);
        for (int k = 0; k < oldTextArray.Length; k++)
        {
            // truncate each line
            newTextLines.Add(string.Concat(oldTextArray[k].Take(MAX_LINE_LENGTH)));
        }
        // Save the cursor position
        var cursorPos = textbox.SelectionStart;
        // To avoid the text change calling back into this event, detach the event while setting the Text property
        textbox.TextChanged -= TextBox_TextChanged;
        // Set the new text
        textbox.Text = string.Join(Environment.NewLine, newTextLines);
        textbox.TextChanged += TextBox_TextChanged;
        // Restore the cursor position
        textbox.SelectionStart = cursorPos;
        // if at the end of the line, the position will advance automatically to the next line, supress that
        if (textbox.SelectionStart != cursorPos)
        {
            textbox.SelectionStart = cursorPos - 1;
        }
    }
    e.Handled = true;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...