下一行输入不同的文字

时间:2018-01-19 13:23:45

标签: c# xaml uwp textbox

我有用于诊断目的的文本框。背后的代码非常简单:

XAML:

<TextBox HorizontalAlignment="Left" Margin="640,20,0,0" TextWrapping="Wrap" Height="280" Width="840" Name="txtDiagnostic" IsHitTestVisible="True" />

C#:

private void AddMessage(string message)
{
    txtDiagnostic.Text += (DateTime.Now.ToString("hh:mm:ss:fff") + " " + message);
}

如何定义每个新输入位于不同的行?因为现在所有的错误只有一长串。

  

14:15:00错误1 14:16:00错误2 14:17:00错误3

而不是像每个错误之间的换行符那样可读:

  

14:15:00错误1
  14:16:00错误2
  14:17:00错误3

3 个答案:

答案 0 :(得分:5)

在每个字符串的末尾添加Environment.NewLine

txtDiagnostic.Text += (DateTime.Now.ToString("hh:mm:ss:fff") + " " + message) + Environment.NewLine;

并确保文本框为capable of multiline

XAML:

<TextBox
  Name="tbMultiLine"
  TextWrapping="Wrap"
  AcceptsReturn="True"                    <-- IMPORTANT
  VerticalScrollBarVisibility="Visible"   <-- IMPORTANT
>

编辑:至于回应通常的string concatination debate,您当然可以使用string.Concat()

String.Concat(txtDiagnostic.Text,DateTime.Now.ToString("hh:mm:ss:fff") , " " , "ERROR....." , Environment.NewLine);

会更快。这是LINQPad的基准代码,包含1000行:

void Main()
{
    Stopwatch sw = new Stopwatch();

    string text = "";
    sw.Start();
    for (int i = 0; i < 1000; i++)
    {
        //text += (DateTime.Now.ToString("hh:mm:ss:fff") + " " + "ERROR.....") + Environment.NewLine;
        String.Concat(text,DateTime.Now.ToString("hh:mm:ss:fff") , " " , "ERROR....." , Environment.NewLine);
    }
    sw.Stop();
    Console.WriteLine("ELAPSED: " + sw.ElapsedMilliseconds);

}

输出:

  

+连接(在我的机器上)16 msek
  Concat需要10 msek

选择自己,你应该知道你想要多少错误信息&#34;通知&#34;用户;)

免责声明:1000行是一个非常糟糕的基准,但我选择它来适应手头的用例。读取超过1000行(甚至1000行)的错误消息并不是我想要使用的软件。如果你开始连接较大的行集(x> 1000),那么你真的应该使用StringBuilder,这也是我提供的字符串连接辩论链接中提到的。

答案 1 :(得分:2)

从源代码中实现Environment.NewLine

.NET 4.6.1中的实现:Source

/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the given
**        platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
    get {
        Contract.Ensures(Contract.Result<String>() != null);
        return "\r\n";
    }
}

所以你可以用\r\n作为string的最后两位数作为输出文本,结果与Mong Zhu的答案完全相同,因为Environment.NewLine是它的实现。

txtDiagnostic.Text += (DateTime.Now.ToString("hh:mm:ss:fff") + " " + message + "\r\n");

如果您使用\n\r\n,则视平台而定。在Windows上,它实际上是\r\n

来自MSDN:

  

包含“\ r \ n”的字符串   非Unix平台或字符串   包含Unix平台的“\ n”。

答案 2 :(得分:1)

您也可以使用AppendText():

this.txtTest.AppendText("blablabla" + Environment.NewLine);
相关问题