Search code examples
wpftextblock

Add new lines on top in TextBlock


I'm working with a TextBlock and Inlines to add new text which contains some information from a HTTP request.

How can I add new text coming from the top instead of a bottom like it works by default?


Solution

  • If your TextBlock has a name and you modify it from code-behind...

    <TextBlock x:Name="MyTextBlock"/>
    

    You can use InsertBefore with FirstInline to add the inline as first element to Inlines.

    MyTextBlock.Inlines.InsertBefore(MyTextBlock.Inlines.FirstInline, new Run("My text to add as first inline."));
    

    If you want to put newlines in between the text that you add, use LineBreak.

    MyTextBlock.Inlines.InsertBefore(MyTextBlock.Inlines.FirstInline, new LineBreak());