Form And Code Unsynched
I have a textbox with some text in it ("hello"). If I change the text to anything else and get the text from the textbox (through the code), I'll get "hello" although I changed it.
In another case, when I change a checkbox's check state, the checkbox won't visually tick (or untick).
Anyone has an idea what's going on and how to sync them?
I've opened a new project, thats the only function on my form :
public void Switch()
{
Checkbox1.Checked = !Checkbox1.Checked;
}
and I call it from the program.cs :
开发者_如何学JAVAstatic MainForm MyForm;
MyForm = new MainForm();
MyForm.Switch();
I assume that you are simply instantiating MainForm
in Main
and then calling Switch
.
Which means that you are not sending the request on the UI Thread.
So, you can Invoke
your code to run on the UI thread:
public void Switch()
{
// true if off of the UI thread, and thus must be Invoked
if (this.InvokeRequired)
{
// off UI thread; put it onto it
this.Invoke(Switch);
}
else
{
// on UI thread
Checkbox1.Checked = ! Checkbox1.Checked;
}
}
You should only interact with the UI from the UI Thread. You should not litter your code with Invoke
s unless you expect to call it off of the UI Thread, or you provide a means for others to do so (some public API).
精彩评论