我正在尝试以2秒的时间间隔更改图片。应该只有一次,而不是无休止的时间。
我用Google搜索了各种替代品,但找不到。就像thread.sleep(2000)一样,因为它冻结了接口,所以不起作用。
item: {
"cert" : "star_example"
"domains"
- "*.example.com"
- "www.example.com example.com"
}
XAML代码
public partial class Window1 : Window
{
private static System.Timers.Timer aTimer;
public void RemoveImage()
{
Image.Source = new BitmapImage(new Uri("path to image 2"));
SetTimer();
}
private void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Image.Source = new BitmapImage(new Uri("path to image 3"));
}
使用此代码,我到达第二张图片,但是到了最后一张图片,您得到了针对图像3的错误System.InvalidOperationException。希望您能为我提供任何解决方案
答案 0 :(得分:1)
请勿将Dispatcher.Invoke
与System.Timers.Timer
一起使用。
相反,使用DispatcherTimer
,它已经在UI线程中调用其Tick处理程序。:
private DispatcherTimer timer;
private void SetTimer()
{
timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
timer.Tick += OnTimerTick;
timer.Start();
}
private void OnTimerTick(object sender, EventArgs e)
{
Image.Source = new BitmapImage(new Uri("path to image 3"));
timer.Stop();
}
答案 1 :(得分:-1)
计时器在UI线程上不起作用,因此如果不调用OnTimedEvent
https://docs.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatcher.invoke?view=netframework-4.7.2
Dispatcher.Invoke
中的控件