programmatic textblock entry with linebreaks

前端 未结 5 1956
挽巷
挽巷 2020-12-20 12:41

How do I programmatically add text with line breaks to a textblock?

If I insert text like this:

helpBlock.Text = \"Here is some text. 

        
相关标签:
5条回答
  • 2020-12-20 12:55

    I have one component XAML

    <TextBlock x:Name="textLog" TextWrapping="Wrap" Background="#FFDEDEDE"/>
    

    Then I pass the string + Environment.NewLine;

    Example:

    textLog.Inlines.Add("Inicio do processamento " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + Environment.NewLine);
    textLog.Inlines.Add("-----------------------------------" + Environment.NewLine);
    

    The result is

    Inicio do processamento 19/08/2019 20:31:13
    -----------------------------------

    0 讨论(0)
  • 2020-12-20 12:57

    You could convert \n to <LineBreak/> programmatically.

        string text = "This is a line.\nThis is another line.";
        IList<string> lines = text.Split(new string[] { @"\n" }, StringSplitOptions.None);
    
        TextBlock tb = new TextBlock();
        foreach (string line in lines)
        {
            tb.Inlines.Add(line);
            tb.Inlines.Add(new LineBreak());
        }
    
    0 讨论(0)
  • 2020-12-20 13:00

    You could just pass in newline \n instead of <LineBreak/>

    helpBlock.Text = "Here is some text. \n Here is \n some \n more.";
    

    Or in Xaml you would use the Hex value of newline

     <TextBlock Text="Here is some text. &#x0a; Here is &#x0a; some &#x0a; more."/>
    

    Both results:

    enter image description here

    0 讨论(0)
  • 2020-12-20 13:08

    Solution:

    I would use "\n" instead of linebreaks. Best way would be use it on this way:

    Resources.resx file:

    myTextline: "Here is some text. \n Here is \n some \n more."
    

    In yours Class:

    helpBlock.Text = Resources.myTextline;
    

    This will looks like:

    Other solution would be to build your string here with Environment.NewLine.

    StringBuilder builder = new StringBuilder();
    builder.Append(Environment.NewLine);
    builder.Append(Resources.line1);
    builder.Append(Environment.NewLine);
    builder.Append(Resources.line2);
    helpBlock.Text += builder.ToString();
    

    Or use here "\n"

    StringBuilder builder = new StringBuilder();
    builder.Append("\n");
    builder.Append(Resources.line1);
    builder.Append("\n");
    builder.Append(Resources.line2);
    helpBlock.Text += builder.ToString();
    
    0 讨论(0)
  • 2020-12-20 13:10

    Use Enviroment.NewLine

    testText.Text = "Testing 123" + Environment.NewLine + "Testing ABC";
    
    StringBuilder builder = new StringBuilder();
    builder.Append(Environment.NewLine);
    builder.Append("Test Text");
    builder.Append(Environment.NewLine);
    builder.Append("Test 2 Text");
    testText.Text += builder.ToString();
    
    0 讨论(0)
提交回复
热议问题