簡體   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