Search code examples
c#wpfdispatcherinvokerequired

C# wpf dispatcher confusion


how should i go about porting this code to wpf?

public void ChangeTextBox(string txt)
    {
        if (textBox1.InvokeRequired)
        {
            Invoke(new UpdateText(ChangeTextBox), new object[] { txt });
        }
        else
        {
            textBox1.Text += txt + "\r\n";
        }
    }

Solution

  • You should be able to do something like this:

    public void ChangeTextBox(string txt)
        {
            if (!textBox1.Dispatcher.CheckAccess())
            {
                textBox1.Dispatcher.Invoke(new UpdateText(ChangeTextBox), new object[] { txt });
            }
            else
            {
                textBox1.Text += txt + "\r\n";
            }
        }
    

    This answer was based upon a SO question and the MSDN Documentation for Dispatcher.