WPF 图像仅在时间跨度完成后更新

WPF Images only update after timespan is done

我的程序需要显示一些文本以显示 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

我的文本仅在时间跨度检查后出现,然后立即隐藏

它没有显示,因为您的代码处于硬循环中,并且您没有给 UI 时间来处理在 DisplayWords() 方法中所做的更改。如果您在 DisplayWords(); 之后放置一个 Application.DoEvents();,它应该允许 OS 时间来更新 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

在异步方法中使用Task.Delay

public async Task ShowText()
{
    DisplayWords();

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

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

    //Hide texts
}