Reputation: 55
I created new Window on a different thread because it has heavy UI operations, that was done to keep my main window run smoothly. Everything works perfectly.
But here is the question:
How I can access newly created window?
After calling Dispatcher.Run()
I can not manipulate visualisationWindow
anymore. I want to keep access to that newly created window object.
Here is how my window created:
private void CreateVisualisationWindow()
{
Thread VisualisationWIndowThread = new Thread(new ThreadStart(ThreadStartingPoint));
VisualisationWIndowThread.SetApartmentState(ApartmentState.STA);
VisualisationWIndowThread.IsBackground = true;
VisualisationWIndowThread.Start();
}
private void ThreadStartingPoint()
{
Visualisation visualisationWindow = new Visualisation();
visualisationWindow.Show();
System.Windows.Threading.Dispatcher.Run();
}
Also I tried accessing it through System.Windows.Threading.Dispatcher.FromThread(VisualisationWIndowThread)
but seems I misunderstand some core things.
Upvotes: 2
Views: 723
Reputation: 301
I simulated your issue using two WPF Window objects and a timer to ensure that the Second Window was created before calling operations on it. Below is my code sample and it updates the second Windows TextBox every five seconds:
private Timer _timer;
private SecondWindow _secondWindow;
public MainWindow()
{
InitializeComponent();
CreateVisualisationWindow();
_timer = new Timer(Callback);
_timer.Change(5000, 5000);
}
private void Callback(object state)
{
UpdateSecondWindowText();
}
private void CreateVisualisationWindow()
{
Thread VisualisationWIndowThread = new Thread(ThreadStartingPoint);
VisualisationWIndowThread.SetApartmentState(ApartmentState.STA);
VisualisationWIndowThread.IsBackground = true;
VisualisationWIndowThread.Start();
}
private void ThreadStartingPoint()
{
_secondWindow = new SecondWindow();
_secondWindow.SecondWindowTextBlock.Text = "Hello";
_secondWindow.Show();
Dispatcher.Run();
}
private void UpdateSecondWindowText()
{
_secondWindow.Dispatcher.BeginInvoke(new Action(() =>
{
_secondWindow.SecondWindowTextBlock.Text = _secondWindow.SecondWindowTextBlock.Text + " World";
}));
}
So the trick is, you need to call the Dispatcher on the second Window in order to gain access to it.
Upvotes: 2