Thanks! I ended up with a slightly different solution, but you definitely pointed me in the right direction with your answer.
For my application, I have many controls mostly, and most calls to the main method come from the main scope, so it was easier to use the default value {get; set} inside MainWindow.xaml.cs (or just define controls in XAML).
In my parent window, behind the code, I run MainWindow in a separate thread like this (simplified example). The key must be defined globally globally, even if it is created inside Window_Loaded ():
public ParentWindow() { InitializeComponent(); } MainWindow main; private void Window_Loaded(object sender, RoutedEventArgs e) { Thread otherThread = new Thread(() => { main = new MainWindow(); main.Show(); main.Closed += (sender2, e2) => main.Dispatcher.InvokeShutdown(); System.Windows.Threading.Dispatcher.Run(); }); otherThread.SetApartmentState(ApartmentState.STA); otherThread.Start(); }
Then, in my MainWindow code, I just interact with the controls as if it were a simple single-threaded application (in my case there is no control over the parent thread from the child thread). However, I can control main from the parent thread as follows:
private void button_Click(object sender, RoutedEventArgs e) { main.Dispatcher.Invoke(new Action(delegate () { main.myControl.myMethod(); })); }
This way I avoid the complexity of defining everything in encoding and using the dispatcher from within the MainWindow.xaml.cs code. There are only a few points in my application where I change main from the parent window, so it was easier for me, but your approach seems the same. Thanks again!
Elemental pete
source share