Search code examples
c#wpfrichtextboxblock

How to add a block to richtextbox


How can I add a new block to the richtextbox.document.blocks collection? In a different thread, a check finds place about how many characters are in the richtextbox.

If the amount is above 25000 chars, i clear up the richtextbox using richtextbox.document.blocks.clear()

But this removes my initial blocks which i had created in the UI-Thread:

Paragraph p = this.richtextbox.Document.Blocks.FirstBlock as Paragraph;
p.Margin = new Thickness(0);

Trying this code in that other thread than the UI-Thread, gives me an invocation exception at runtime. Because 'p' is null.

What am i missing guys?


Solution

  • The code you showed does not create any blocks it just gets the first one which usually will be there by default so if you clear all blocks you will first need to add a new one using something like:

    var p = new Paragraph();
    richtextbox.Document.Blocks.Add(p);
    p.Margin = ...;
    

    You can just have an if which checks the number of blocks, if there is more than one get the first one with you original code if not create and add it.