I am starting a Window from a different application. Whenever I start the Window, it is done from a different thread. The first time I start the Window, everything works fine. Every later attempt fails with the error: The calling thread cannot access this object because a different thread owns it.
I used to assign the DataContext in the Xaml like this:
<UserControl.DataContext>
<viewModels:MyViewModel/>
</UserControl.DataContext>
The error stopped, when I changed it to assign the ViewModel from the code behind like this:
public MyView() {
InitializeComponent();
DataContext = new MyViewModel();
}
According to an answer at MSDN these two approaches should be equivalent.
Why do I get different results? Is there a way to make my first approach work (as I would prefer it)?
Edit:
The control is initialized in another Xaml:
<userControls:MyView Grid.Column="2" x:Name="MyView" Grid.ColumnSpan="1" ></userControls:MyView>
The window itself is started using
AutoResetEvent are = new AutoResetEvent(false);
Thread thread = new Thread(() => {
MyMainWindow form = new MyMainWindow(someObject);
form.Closed += (sender2, e2) => {
Dispatcher.CurrentDispatcher.InvokeShutdown();
are.Set();
};
form.Show();
Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
are.WaitOne();
Edit 2:
After some debugging I found the root cause. I was using a custom implementation of a messaging system based on the Prism Event Aggregator. When MyMainWindow was closed, I didn't clear all the subscriptions.