简体   繁体   English

在编写新文本之前清除RichTextBox

[英]Clear RichTextBox Before Writing New Text

I'm using Visual Studio, WPF, C#, XAML. 我正在使用Visual Studio,WPF,C#,XAML。

I have a RichTextBox that C# writes text to on button press. 我有一个RichTextBox,C#在按下按钮时就将文本写入其中。

Each time the button is pressed it appends the new text to the RichTextBox, leaving the old text. 每次按下按钮时,都会新文本追加到RichTextBox中,而保留旧文本。

I need it to clear the old text before writing the new, so it doesn't stack up. 在编写新文本之前,我需要它清除旧文本,因此它不会堆积。

XAML XAML

<RichTextBox Name="richTextBox1" IsUndoEnabled="False" />

C# C#

Clear 明确

richTextBox1.Document.Blocks.Clear();

public static System.Windows.Media.Brush White = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFFFFF"));
public static Paragraph paragraph = new Paragraph();

// Button
private void btnWrite_Click(object sender, RoutedEventArgs e) {

    //Clear() put here, does nothing


    // New Document
    richTextBox1.Document = new FlowDocument(paragraph);


    //Clear() put here works but wont write new text, stays blank


    //begin writing
    richTextBox1.BeginChange();

        //Clear() put here works but wont write new text, stays blank

        //write text
        paragraph.Inlines.Add(new Run("Hello, World.") { Foreground = White });

    //end writing
    richTextBox1.EndChange();


    richTextBox1.UpdateLayout(); //does nothing
}

There are three ways to clear the text of the RichTextBox: 有三种清除RichTextBox文本的方法:

  1. Use the clear method: 使用清除方法:

     richTextBox1.Document.Blocks.Clear(); 

    As I mentioned, this way doesn't work for you 正如我提到的,这种方式对您不起作用

  2. Select all of your RichTextBox and set the Text to "": 选择所有RichTextBox并将“文本”设置为“”:

     richTextBox1.SelectAll(); richTextBox1.Selection.Text = ""; 

    Do this, before you start to change. 在开始更改之前,请执行此操作。

  3. Use TextRange, to get the text and clear it with "": 使用TextRange获取文本并使用“”清除它:

     TextRange txt = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd); txt.Text=""; 

My answer is a conclusion from this question: how to clear text content in RichTextBox 我的答案是从这个问题得出的结论: 如何清除RichTextBox中的文本内容


Update : You can try the following: 更新 :您可以尝试以下操作:

  1. Create an object from FlowDocument: 从FlowDocument创建对象:

     FlowDocument ObjFdoc = new FlowDocument(); 
  2. Create a paragraph: 创建一个段落:

     Paragraph paragraph = new Paragraph(); paragraph.Inlines.Add(new Run("Hello, World.") { Foreground = White }); 
  3. Add the paragraph to the FlowDocument: 将段落添加到FlowDocument:

     ObjFdoc.Blocks.Add(ObjPara1); 
  4. Set the RichtTextBox.Document: 设置RichtTextBox.Document:

     richTextBox1.Document=ObjFdoc; 

Every time you call your method, it will be generate a new flowdocument and gc deletes the old flowdocuments for you. 每次调用方法时,它将生成一个新的flowdocument,而gc会为您删除旧的flowdocument。

I need 50 reputation to comment... 我需要50声望才能发表评论...

Is there a particular reason for you to assign a new FlowDocument to the RichTextBox every time the button is pressed? 每次按下按钮时,您是否有特定的原因将新的FlowDocument分配给RichTextBox

You're clearing the documents content in the Clear() method and than attach a new FlowDocument object with the entire paragraph to the RichTextBox , thus appending the new text to the same paragraph. 您正在Clear()方法中Clear()文档内容,然后将带有整个段落的新FlowDocument对象附加到RichTextBox ,从而将新文本附加到同一段落。

Try removing the richTextBox1.Document = new FlowDocument(paragraph); 尝试删除richTextBox1.Document = new FlowDocument(paragraph); line. 线。

Because the text was added in a paragraph (Block) contained in your FlowDocument( richtextBox1.Document ) it has to be cleared using this code: 由于文本是添加到FlowDocument( richtextBox1.Document )包含的段落(块)中的,因此必须使用以下代码清除:

 paragraph.Inlines.Clear(); 

Explanation: The issue here is that you are clearing all blocks from your FlowDocument, including your single paragraph so next time you want to append text in that paragraph it won't work, of course, the text is added to the paragraph referenced by paragraph but it is not part of the document any more. 说明:这里的问题是,您正在清除FlowDocument中的所有块,包括单个paragraph因此,下次您要在该段落中添加文本时,它将不起作用,当然,该文本将添加到该段落引用的paragraph但它不再是文档的一部分。

Here are some unit Tests 这是一些单元测试

 [Apartment(ApartmentState.STA)]
    public class Tests
    {
        public static System.Windows.Media.Brush White = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFFFFF"));
        protected Paragraph paragraph;
        protected RichTextBox richTextBox1;

        [SetUp]
        public void Setup()
        {
            richTextBox1 = new RichTextBox();
            paragraph = new Paragraph();
            richTextBox1.Document = new FlowDocument(paragraph);
        }

        /// <summary>
        /// This reproduce the issue
        /// </summary>
        [Test]
        public void Adding_Text_After_Blocks_Clear_Should_Not_Work_The_issue()
        {
            paragraph.AddText("Hello, World!");

            string content1 = richTextBox1.GetText();

            Assert.AreEqual("Hello, World!", content1);

            richTextBox1.Document.Blocks.Clear();

            string content2 = richTextBox1.GetText();

            Assert.AreEqual("", content2);

            paragraph.AddText("Howdy!");

            string content3 = richTextBox1.GetText();

            //are not equal
            Assert.AreNotEqual("Howdy!", content3);
        }

        [Test]
        public void Adding_TextAfter_Paragraph_Clear_Should_Work_Solution()
        {
            paragraph.AddText("Hello, World!");

            string content1 = richTextBox1.GetText();

            Assert.AreEqual("Hello, World!", content1);

            paragraph.Inlines.Clear();

            string content2 = richTextBox1.GetText();

            Assert.AreEqual("", content2);

            paragraph.AddText("Howdy!");

            string content3 = richTextBox1.GetText();

            Assert.AreEqual("Howdy!", content3);
        }

        /// <summary>
        /// Keep in mind tha if the  RichTextBox is not readonly, deleting text with CTRL-A + DELETE 
        /// Causes the same issues.
        /// </summary>
        [Test]
        public void Clearing_Blocks_Should_Remove_All_Paragraphs_The_Cause_of_issue()
        {
            paragraph.AddText("Hello, World!");

            string content1 = richTextBox1.GetText();

            Assert.AreEqual("Hello, World!", content1);

            var blocksBefore = richTextBox1.Document.Blocks.ToArray();

            Assert.IsTrue(ReferenceEquals(paragraph, blocksBefore[0]));

            richTextBox1.Document.Blocks.Clear();

            var blocksAfter = richTextBox1.Document.Blocks.ToArray();

            Assert.AreEqual(0, blocksAfter.Length);
        }


        [Test]
        public void Added_New_Text_after_Blocks_Clear_Should_Work()
        {
            paragraph.AddText("Hello, World!");

            string content1 = richTextBox1.GetText();

            Assert.AreEqual("Hello, World!", content1);

            richTextBox1.Document.Blocks.Clear();

            string content2 = richTextBox1.GetText();

            Assert.AreEqual("", content2);

            var p = new Paragraph();

            p.AddText("Howdy!");

            //Add this to the blocks collection!!!!
            richTextBox1.Document.Blocks.Add(p);

            string content3 = richTextBox1.GetText();

            Assert.AreEqual("Howdy!", content3);
        }
    }

    public static class RTBExtentions
    {
        public static string GetText(this RichTextBox rtb)
        {
            return new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd).Text.TrimEnd();
        }
        public static void AddText(this Paragraph paragraph, string textToAdd, Brush foregroundColor = default(Brush))
        {
            paragraph.Inlines.Add(new Run(textToAdd) { Foreground = foregroundColor });
        }

        public static Block[] ToArray(this BlockCollection blocks)
        {
            List<Block> elements = new List<Block>();

            foreach (var item in blocks)  {  elements.Add(item);  }

            return elements.ToArray();
        }
    }

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

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