0

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 


    }
}
vasu
  • 79
  • 5
  • Where are you trying to access an attribute? What attribute are you trying to access? There isn't enough information to see what you have tried to make this work. – Martin Noreke May 25 '15 at 17:47
  • @MartinNoreke I tried to elaborate. Suggestions appreciated. – vasu May 25 '15 at 17:58

2 Answers2

3
  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));
Community
  • 1
  • 1
Emond
  • 50,210
  • 11
  • 84
  • 115
  • would be thankful if you could elaborate on point one. I already have a reference to Application i.e. a . But I cannot get a reference to my current WPF application (how do I get that?). Without it, I cannot reference "TheTextBox" here. – vasu May 26 '15 at 07:20
  • What do you mean by the current application? The code only contains a single application and you can get it by using App.Current – Emond May 26 '15 at 08:55
0

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.

Martin Noreke
  • 4,066
  • 22
  • 34