将 Debug.WriteLine 流重定向到文本块

Mat*_*ger 3 c# silverlight windows-phone-7 windows-phone

我想将调试标准输出流重定向到文本块。有没有一种简单的方法可以做到这一点?

谢谢。

wal*_*5hy 5

添加自定义 Tracelistener 到您要收听的输出。

这是一个简单的类,它扩展了 TraceListener 并获取要在构造函数中更新的 TextBox

class TextBoxTraceListener : TraceListener
{
    private TextBox tBox;

    public TextBoxTraceListener(TextBox box)
    {
        this.tBox = box;
    }

    public override void Write(string msg)
    {
        //allows tBox to be updated from different thread
        tBox.Parent.Invoke(new MethodInvoker(delegate()
        {
            tBox.AppendText(msg);
        }));
    }

    public override void WriteLine(string msg)
    {
        Write(msg + "\r\n");
    }
}
Run Code Online (Sandbox Code Playgroud)

在表单代码中,在创建表单句柄后初始化 TextBoxTraceListener:

    protected override void OnHandleCreated(EventArgs e)
    {
        TextBoxTraceListener tbtl = new TextBoxTraceListener(TheTextBox);
        Debug.Listeners.Add(tbtl);
        Debug.WriteLine("Testing Testing 123");
    }
Run Code Online (Sandbox Code Playgroud)

完毕。如果你想听 Trace 而不是 Debug 输出:

Trace.Listeners.Add(tbtl);
Run Code Online (Sandbox Code Playgroud)

  • 我建议使用 `tBox.AppendText(msg)` 而不是 `tBox.Text += msg` (2认同)