The Code Behind of a WinForm is crashing with The calling thread must be STA, because many UI components require this.
, when trying to create a WPF user control, using myWpfUserControl = new MyWpfUserControl();
. It seems to be crashing in the base user control constructor.
The entry point to my application is ApplicationStartup
in App.xaml.cs
, that has [STAThread]
on it. I am not using threading at all, and I can see in the Threads pane in Visual Studio when it crashes that it is on the Main Thread
.
EDIT: It used to work.
Here is the skeleton of my code:
[STAThread]
private void ApplicationStartup(object sender, StartupEventArgs e)
{
LogonFormEventListener listener = new LogonFormEventListener();
Logon.LogonFormEvent += new Logon.ClassFormEventHandler(listener.TestEventRaised);
Logon logon = new Logon();
logon.ShowDialog();
}
public partial class Logon : Form
{
private void OKbutton_Click(object sender, EventArgs e)
{
if(LogonFormEvent !=null) LogonFormEvent(this, null);
}
}
public class LogonFormEventListener
{
public void TestEventRaised(Logon o, EventArgs e)
{
MainForm mainForm = new MainForm();
mainForm.ShowDialog();
}
}
public partial class MainForm : Form
{
MyWpfUserControl myWpfUserControl;
private void mainMenu_ItemClick(object sender, MenuBar.ItemEventArgs e)
{
switch (e.Item.Key)
{
case "myAction":
myWpfUserControl = new MyWpfUserControl(); //CRASH
...
break;
}
}
}
The user control crashes in the base constructor, before any of the code in my user control runs, so there is no point showing the user control code (I think).
Any ideas would be appreciated.