繁体   English   中英

限制多行文本框中的行长

[英]Limit line length in multiline textbox

我需要限制用户可以在多行文本框中输入的单行字符数。 我有一个函数可以对输入的数据执行此操作,但不能对剪切和粘贴的数据执行此操作。

我尝试将文本框读入数组,使用子字符串,然后复制回文本字符串,但此代码(已发布)引发异常。

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;
    }

这可以满足您的要求:

当您键入以及粘贴或以其他方式更改文本时,它会截断任何长度超过 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM