Search code examples
c#wpf

How can I insert a newline into a TextBlock without XAML?


I have created a WPF TextBlock inside a Label in code (XAML is not possible in my case) as follows:

Label l = new Label();
TextBlock tb = new TextBlock();
l.Content = tb;

I then come to a situation where I need to set the .Text property of TextBlock containing a new line, such as:

tb.Text = "Hello\nWould you please just work?";

I have tried numerous encodings (HTML encoding, ASCII encoding, etc.) of various newline combinations (carriage return, linefeed, carriage return plus linefeed, linefeed plus carriage return, double linefeed, double carriage return, etc... ad nauseum).

  • Answers should contain absolutely no XAML.
  • Answers should assume that the original objects were created using C# code and not XAML.
  • Answers should not refer to binding of WPF properties. No binding is being used. The "Text" property of the "TextBlock" object is being set. The newline must be inserted there.

If this is impossible, please let me know how I can programmatically add newlines by dynamically replacing each newline in an arbitrary input String into a LineBreak object (or whatever is needed to get this working). The input String will have arbitrary (readable text) contents that I am unable to anticipate in advance because the text itself is dynamic (user-defined); the source strings will have the linefeed character (aka LF, aka \n) but I can easily replace that with whatever is needed.

Also, if it is easier to do this with a Label directly rather than a TextBlock in a Label, that is good too -- I can use that. I just need a control with automatic plain text line wrapping.


Solution

  • You have a few choices:

    Use the Environment.NewLine property:

    TextBlock tb = new TextBlock();
    tb.Text = "Hello" + Environment.NewLine + "Would you please just work?";
    

    Or, manually add Runs and LineBreaks to the TextBlock:

    TextBlock tb = new TextBlock();
    tb.Inlines.Add(new Run("Hello"));
    tb.Inlines.Add(new LineBreak());
    tb.Inlines.Add(new Run("Would you please just work?"));