OK, here's what I am trying to do. I have a nasty WPF control (that I am forced to use) that requires a parent with an HWND (because it contains some Windows.Forms stuff) and can be very unresponsive at times. This causes my WPF app to also get bogged down and become unresponsive (less responsive would be more accurate). I would like to move this control onto its own Dispatcher so that my app's Dispatcher isn't tied up when the control becomes unresponsive.
I have tried to create a Window derived class to host the Control. I launch it on an STA thread and do a Dispatcher.Run(). So far all is good. The badness happens when I try to add that Window derived class to the topmost Grid inside my app. I get the "The calling thread cannot access this object because another thread owns it." exception.
XAML for my app:
<Window
x:Class="MyAppWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid
ClipToBounds="True"
x:Name="mainGrid"
Grid.Row="1">
</Grid>
</Window>
myApp.cs
public class MyAppWindow :Window
{
CrapControlWindow crapControlWindow;
Dispatcher crapControlWindowDispatcher;
Dispatcher myAppDispatcher;
public MyAppWindow()
{
myAppDispatcher = Dispatcher.CurrentDispatcher;
Thread launchThread = new Thread(new ThreadStart(crapControlHostLauncher));
launchThread.IsBackground = true;
launchThread.ApartmentState = ApartmentState.STA;
launchThread.Start();
}
public Initialize()
{
mainGrid.Children.Add(crapControlWindow); <--- Fails Here
}
void crapControlHostLauncher()
{
crapControlWindowDispatcher = Dispatcher.CurrentDispatcher;
Dispatcher.CurrentDispatcher.BeginInvoke((Action)delegate()
{
crapControlWindow = new crapControlWindow();
});
Dispatcher.Run();
}
}
XAML for child window:
<Window x:Class="CrapControlWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Crappy Control Window" Height="300" Width="300">
<Grid x:Name="mainGrid">
<CrapControl
Grid.Row="1"
Name="crapControl1"
ClipToBounds="True"
Margin="0,4,0,4" />
</Grid>
</Window>
I've tried various permutations of the failing line - crapControlWindowDispatcher.Invoke, myAppDispatcher.Invoke etc. NADA! Same exception...
So lay it on me - am I crazy? other strategies? Can I make this work?
Thanks for your help!