更改WPF中的按钮内容

时间:2013-03-07 18:51:33

标签: c# wpf button mouseevent

我有:

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 ,但Content上的Button不会更改。为什么?我能做错什么?

2 个答案:

答案 0 :(得分:2)

嗨,你的for循环是否正确?它应该是i <2而不是i&gt; 2

 for (int i = 0; i < 2; i++)
        {

答案 1 :(得分:0)

您的for循环永远不会执行,因为您的条件有错,请将其更改为以下代码:

for (int i = 0; i < 2; i++)

此外,您应该使用BackgroundWorkermsdn)动态更新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();
}