Trace listener to write to a text box (WPF application)

kjv picture kjv · Sep 7, 2009 · Viewed 15.1k times · Source

For my WPF application I do logging to a text file using a TextWriterTraceListener. How can I also display the Trace output to a textbox?

Answer

nos picture nos · Sep 7, 2009

I use this for C# winforms, should be easily adjustable to wpf

public class MyTraceListener : TraceListener
{
    private TextBoxBase output;

    public MyTraceListener(TextBoxBase output) {
        this.Name = "Trace";
        this.output = output;
    }


    public override void Write(string message) {

        Action append = delegate() {
            output.AppendText(string.Format("[{0}] ", DateTime.Now.ToString()));
            output.AppendText(message); 
        };
        if (output.InvokeRequired) {
            output.BeginInvoke(append);
        } else {
            append();
        }

    }

    public override void WriteLine(string message) {
        Write(message + Environment.NewLine);
    }
}

Use it like

TraceListener debugListener = new MyTraceListener (theTextBox);
Debug.Listeners.Add(debugListener);
Trace.Listeners.Add(debugListener);

Remember to Trace/Debug.Listeners.Remove(debugListener); when you don't need it anymore.