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).
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.
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 Run
s and LineBreak
s 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?"));