【问题标题】:Remove empty blocks from the Richtextbox without losing formatting从 Richtextbox 中删除空块而不丢失格式
【发布时间】:2019-04-12 12:37:13
【问题描述】:

我想从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);

【问题讨论】:

    标签: c# wpf richtextbox


    【解决方案1】:

    string findword = findWord.Text; string 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("", lines);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 1970-01-01
      • 2012-10-20
      相关资源
      最近更新 更多