从Richtextbox中删除空块,而不会丢失格式

时间:2019-04-12 12:37:14

标签: c# wpf richtextbox

我想从我的RichTextBoxTextRange删除空白/多余的空格和回车符。下面是我尝试的代码。但是,尽管我能够删除空白区域,但同时格式也丢失了。

我知道我设置textRange.Text的那一刻丢失了格式。

我不知道该如何前进。

string findword = findWord.Text;
string replaceword = replaceText.Text;

        TextRange textRange = LoadXamlPackage(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);

        string[] lines = textRange.Text.Trim().Split('\r');

        for (int i = 0; i < lines.Count(); i++)
        {
            if (lines[i].Contains(findword) && replaceword == string.Empty)
            {
                lines[i] = "";
            }
        }

        textRange.Text = string.Join(" ", lines);

1 个答案:

答案 0 :(得分:0)

string findword = findWord.Text; 字符串replaceword = replaceText.Text;

    TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);

    string[] lines = textRange.Text.Trim().Split('\r');

        for (int i = 0; i < lines.Count(); i++)
        {
            if (lines[i].Contains(findword) && replaceword == string.Empty)
            {
                lines[i] = "";
            }
        }
        //textRange.Text = string.Join("", lines);         

        string rtf = string.Empty;
        MemoryStream objmemoryStream = new MemoryStream();
        textRange.Save(objmemoryStream, DataFormats.Rtf);
        rtf = System.Text.ASCIIEncoding.Default.GetString(objmemoryStream.ToArray());           
        rtf = rtf.Replace(findword, replaceword);  
        MemoryStream objmemoryStream1 = new MemoryStream(System.Text.ASCIIEncoding.Default.GetBytes(rtf));
        rtfTestResult.SelectAll();
        rtfTestResult.Selection.Load(objmemoryStream1, DataFormats.Rtf);

当我取消注释以下行时,格式将完全丢失-  textRange.Text = string.Join(“”,行);