Xander van den berg
Xander van den berg

Reputation: 69

How to change a picture with a timer

I'm trying to change a picture with a 2 seconds time laps. It should be only once and not an unanding time laps.

I googled all kinds of altenitives but I couldn't find it. Like thread.sleep(2000) doesn't work because it freezes the interface.

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 code

<Window

<Image Source="path to image 1" Grid.Row="1" Grid.Column="8" 
Name="Image" Stretch="None" HorizontalAlignment="Center" 
VerticalAlignment="Center"></Image>

</Grid>
</Window>

With this code I get to the second picture but as it is getting to the last picture you get an error System.InvalidOperationException for image 3. Hope you could help me with any solution

Upvotes: 0

Views: 580

Answers (2)

Clemens
Clemens

Reputation: 128061

Do not use Dispatcher.Invoke with a System.Timers.Timer.

Instead, use a DispatcherTimer, which already calls its Tick handler in the UI thread.:

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();
}

Upvotes: 2

Ivan I
Ivan I

Reputation: 9990

Timer does not work on UI thread, so you can't change the controls in your OnTimedEvent without calling Dispatcher.Invoke https://learn.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatcher.invoke?view=netframework-4.7.2

Upvotes: 0

Related Questions