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

问题描述 投票:3回答:2

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

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

c# wpf timespan
2个回答
1
投票

在异步方法中使用Task.Delay

public async Task ShowText()
{
    DisplayWords();

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

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

    //Hide texts
}

-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
© www.soinside.com 2019 - 2024. All rights reserved.