c# - 如何使用计时器更改图片
问题描述
我正在尝试以 2 秒的时间间隔更改图片。它应该只有一次,而不是无限的时间圈。
我用谷歌搜索了各种替代品,但找不到。像 thread.sleep(2000) 一样不起作用,因为它冻结了界面。
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"));
}
XAML 代码
<Window
<Image Source="path to image 1" Grid.Row="1" Grid.Column="8"
Name="Image" Stretch="None" HorizontalAlignment="Center"
VerticalAlignment="Center"></Image>
</Grid>
</Window>
使用此代码,我可以到达第二张图片,但是当它到达最后一张图片时,您会收到错误 System.InvalidOperationException for image 3。希望您能帮助我解决任何问题
解决方案
不要Dispatcher.Invoke
与System.Timers.Timer
.
相反,使用 a 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();
}
推荐阅读
- android - Android将我自制的CA证书识别为用户证书,并没有正确安装
- javascript - 将乘法结果格式化为小数点后 2 位
- excel - 使用“cell.value < Date(now())”填充列表框
- javascript - 在 JavaScript 上访问 DOM
- javascript - 带有双引号的 JAVA SCRIPT var 到 PHP 并返回用于自动填充
- php - 如果条件在href标签内,我该如何写?
- anaconda - Anaconda 5.3 安装 RStudio 时出错,说离线模式
- django - 在自定义 ScopedRateThrottle 中访问 URL 参数变量
- python - Pandas - 删除 na 的功能
- python - lightGBM 预测相同的值