c#-更改WPF中的按钮内容

我有:

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";
}

当我在“按钮”上输入时,我只能看到“鼠标输入”,但“按钮”上的内容不会更改.为什么?我能做错什么?

最佳答案
因为条件错误,您的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();
}

转载注明原文:c#-更改WPF中的按钮内容 - 代码日志