by david
22. September 2009 09:01
Recently I needed to open a new WPF window on a new thread. I was helped a great deal by this article, however the window that I needed to open did not have parameterless constructor. In the end, this is the code that I came up with:
private void NewWindowThread<T,P>(Func<P, T> constructor, P param) where T : Window
{
Thread thread = new Thread(() =>
{
T w = constructor(param);
w.Show();
w.Closed += (sender, e) => w.Dispatcher.InvokeShutdown();
System.Windows.Threading.Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
This method, uses generics to specify the Type of the window that you're creating as well as the Type of the parameter passed to its constructor, for example:
string t = "Hello World!";
NewWindowThread<TitleWindow, string>(c => new TitleWindow(c), t);
Would work when TitleWindow was declared like this:
public class TitleWindow : Window
{
public TitleWindow(string title)
{
this.Title = title;
}
}
Now I can open different types of window on a new thread and pass parameters to them.