WPF图片仅在时间跨度后更新

时间:2018-11-03 04:09:55

标签: c# wpf timespan

我的程序需要显示一些文本以显示x秒。 问题在于,仅在完成时间跨度检查之后才显示文本。 这是我的代码:

        // Clicks button to show texts

        //Displays text wanted basicly Text.Visibility =Visibility.Visible;
        DisplayWords();

        //Waits x amount of seconds before hidden them
        int nbOfSecondsToWait = Convert.ToInt32(SecondAffichage.Value);
        DateTime timeNow;
        timeNow = DateTime.Now;
        TimeSpan timePassed = (DateTime.Now - timeNow);
        TimeSpan timePassedWanted = new TimeSpan(0, 0, nbOfSecondsToWait);
        while (timePassed < timePassedWanted)
        {
            timePassed = DateTime.Now - timeNow;

        }

        //Hide texts

我的文本仅在时间间隔检查后显示,然后立即被隐藏

2 个答案:

答案 0 :(得分:1)

在异步方法中使用Task.Delay

public async Task ShowText()
{
    DisplayWords();

    int nbOfSecondsToWait = Convert.ToInt32(SecondAffichage.Value);

    await Task.Delay(TimeSpan.FromSeconds(nbOfSecondsToWait));

    //Hide texts
}

答案 1 :(得分:-1)

之所以没有显示,是因为您的代码处于硬循环中,并且您没有给UI时间来处理在DisplayWords()方法中所做的更改。如果您在Application.DoEvents();后面紧跟DisplayWords();,它将使操作系统有时间更新UI。

您也可以改为:

// Clicks button to show texts

//Displays text wanted basicly Text.Visibility =Visibility.Visible;
DisplayWords();
Application.DoEvents();

//Waits x amount of seconds before hidden them
System.Threading.Thread.Sleep(nbOfSecondsToWait * 1000);

//Hide texts