消息框显示太早 - C#
我刚刚开始接触 C# 编程世界,在我的代码中遇到了一个小故障,导致设计被毁。
由于某种原因,当我尝试更改文本框中的文本时,直到显示消息框(位于更改文本的代码下方)之前,它在视觉上不会发生变化。我正在为 WP7 编程,如果这改变了什么的话。单击按钮即可运行。
下面是我的代码:
private void Draw()
{
Random random = new Random((int)DateTime.Now.Ticks);
number[0] = random.Next(0, 9);
number[1] = random.Next(0, 9);
number[2] = random.Next(0, 9);
no1.Text = number[0].ToString();
no2.Text = number[1].ToString();
no3.Text = number[2].ToString();
MessageBox.show("Example message");
}
I am just starting off with the world of programming C#, and have come across a small glitch in my code which causes the design to be ruined.
For some reason, when I am trying change the text in a textbox, it does not visually change until a messagebox has been displayed, which is underneath the code to change the text. I am programming for WP7, if that changed anything. It runs on a button click.
Below is my code:
private void Draw()
{
Random random = new Random((int)DateTime.Now.Ticks);
number[0] = random.Next(0, 9);
number[1] = random.Next(0, 9);
number[2] = random.Next(0, 9);
no1.Text = number[0].ToString();
no2.Text = number[1].ToString();
no3.Text = number[2].ToString();
MessageBox.show("Example message");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 Russell Troywest 指出的那样,您的代码在 UI 线程上执行,该线程与负责更新图形界面的线程完全相同。因此,在函数退出之前,文本框的视觉表示不会更新。
一个简单的解决方案是延迟消息框的执行:
这样,您的
draw
方法将退出而不显示消息框,然后UI线程将在刷新界面后立即显示它。As Russell Troywest pointed out, your code is executing on the UI thread, the very same thread that is in charge of updating the graphical interface. Therefore, the visual representation of the textbox won't be updated until your function exits.
A simple solution is to delay the execution of your messagebox:
This way, your
draw
method will exit without displaying the Message Box, then the UI thread will display it as soon as it's done refreshing the interface.