vasu
vasu

Reputation: 89

Accessing attributes of a WPF application from another thread in main application

I started a WPF application on a thread of my main application.

Now I want to access a text box in this WPF application from the main thread.

I was trying to use dispatchers but I could not figure out a way.

Here is my code

  class program
{
    public static event MyEventHandler event1;
    static Application a;
    static void fun()
    {
        a = new Application();
        a.StartupUri = new Uri("MainWindow.xaml", System.UriKind.Relative);
        //a.initializeComponent();
        a.Run();

    }

     //[STAThread]
    static void Main(string[] args)
    {
        Thread newThread = new Thread(new ThreadStart(fun));
        newThread.SetApartmentState(ApartmentState.STA);
        newThread.Start();
        Trace.WriteLine("rest");
        //I WANT TO ACCESS THE TEXT BOX FROM HERE 


    }
}

Upvotes: 0

Views: 168

Answers (2)

Martin Noreke
Martin Noreke

Reputation: 4146

You will probably need to do something like this to loop the active windows of the application to find the window you need, then call a method on that window to get the actual text box element you need.

    public void AccessTextBox(string windowName, string textBoxName)
    {
        foreach (Window windowToCheck in a.Windows)
        {
            if (!windowToCheck.Name.Equals(windowName, textBoxName))
                continue;
            windowToCheck.Dispatcher.Invoke(((WindowTypeName)windowToCheck).AccessTextBox(textBoxName));
        }
    }

The Dispatcher.Invoke call is a call that puts you on the UI thread, executes a call the the specified method, and returns to your current thread.

This is psuedo-code (quite ugly too :) ), but should put you on the right path.

Upvotes: 0

Emond
Emond

Reputation: 50682

  1. the main thread needs a reference to the window and/or textbox

    • Have the thread that creates the window/textbox put a reference to the window/textbox in a static variable
  2. When the main thread wants to access the textbox it has to switch to the thread that created the textbox and get the result from that thread.

From an answer on that question:

string x;
TheTextBox.Dispatcher.BeginInvoke((Action)(() => x = TheTextBox.Text));

Upvotes: 3

Related Questions