更改WPF中的按钮内容
本文关键字:按钮 WPF 更改 | 更新日期: 2023-09-27 18:02:54
我有:
private void button1_MouseEnter(object sender, EventArgs e)
{
for (int i = 0; i > 2; i++)
{
button1.Content = Convert.ToString(i);
System.Threading.Thread.Sleep(1000);
}
tekst.Text = "Mouse Enter";
}
当我进入Button
时,我只看到 Mouse Enter
,但Button
上的Content
没有变化。为什么?我能做错什么?
你的for循环正确吗?应该是i<2而不是i>2
for (int i = 0; i < 2; i++)
{
你的for循环永远不会执行,因为你有错误的条件,将其更改为以下代码:
for (int i = 0; i < 2; i++)
你也应该使用BackgroundWorker
(msdn)来动态更新你的GUI。
private void button1_MouseEnter(object sender, MouseEventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate
{
for (int i = 0; i < 2; i++)
{
this.Dispatcher.Invoke((Action)(() => { btn.Content = Convert.ToString(i); }));
System.Threading.Thread.Sleep(1000);
}
};
worker.RunWorkerCompleted += delegate { tekst.Text = "Mouse Enter"; };
worker.RunWorkerAsync();
}