C
C#6mo ago
Turwaith

Launching WPF Windows via code when wpf is not startup project

My solution consists of two project. One is a console application and is the startup project, the other one is a wpf project. The two projects communicate with each other using an interface. Now one method that is called via the interface launches the MainWindow of the wpf project. I know that wpf gui applications need to run on the [STAThread] and I know how to declare that, but it does not seem possible in my case. I have added the flag to literally every single method in the call stack that opens the MainWindow and it still threw me an exception saying it was not run on the STAThread. So that doesn't seem to work out. I then have tried calling it in a specifically declared thread, as you can see in the code block below. But then, as soon as I close the window and reopen it, it says Cannot create more than one System.Windows.Application instance in the same AppDomain . Don't I dispose the Application object correctly?
public class GradeAssigner : IGradeAssigner
{
private static Application? _app;
private static readonly object _lock = new object();
public bool GetGradeAssignments(List<string> customerGrades)
{
var thread = new Thread(() =>
{
lock (_lock)
{
if (_app == null)
{
_app = new Application();
_app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
}
var viewModel = new MainViewModel(customerGrades);
var mainWindow = new MainWindow(viewModel);
mainWindow.Closed += (s, e) =>
{
mainWindow.Dispatcher.InvokeShutdown();
_app = null;
};
_app.Run(mainWindow);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return true;
}
}
public class GradeAssigner : IGradeAssigner
{
private static Application? _app;
private static readonly object _lock = new object();
public bool GetGradeAssignments(List<string> customerGrades)
{
var thread = new Thread(() =>
{
lock (_lock)
{
if (_app == null)
{
_app = new Application();
_app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
}
var viewModel = new MainViewModel(customerGrades);
var mainWindow = new MainWindow(viewModel);
mainWindow.Closed += (s, e) =>
{
mainWindow.Dispatcher.InvokeShutdown();
_app = null;
};
_app.Run(mainWindow);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return true;
}
}
1 Reply
Turwaith
TurwaithOP6mo ago
Also, launching the window using Application.Current.Dispather.Invoke does not work since Application.Current will be null as the wpf project is not the startup project
Want results from more Discord servers?
Add your server