首页 > 解决方案 > 如何使用计时器更改图片

问题描述

我正在尝试以 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。希望您能帮助我解决任何问题

标签: c#wpfimagetimer

解决方案


不要Dispatcher.InvokeSystem.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();
}

推荐阅读