1

So i'm trying to loop through a folder and change the image source each 2 seconds.

I think my code is right, but I seem to be missing something since my image won't update, but I don't get an error.

The code populates my array of files so it finds the pictures, I'm just doing something wrong to set the image source.

XAML code

<Grid>
       <Image x:Name="Picture" Source="{Binding ImageSource}"  Width="980" Height="760" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="350,50,0,0"></Image>
 <Grid>

C# code

 private string[] files;
    private System.Timers.Timer timer;

    private int counter;
    private int Imagecounter;

    Uri _MainImageSource = null; 

    public Uri MainImageSource {
        get 
        {
            return _MainImageSource; 
        } 
        set 
        {
            _MainImageSource = value;
        } 
    }

    public IntroScreen()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(this.MainWindow_Loaded);
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {

        setupPics();
    }

    private void setupPics() 
    {
        timer = new System.Timers.Timer();
        timer.Elapsed += new ElapsedEventHandler(timer_Tick);
        timer.Interval = (2000);
        timer.Start();

        files = Directory.GetFiles("../../Resources/Taken/", "*.jpg", SearchOption.TopDirectoryOnly);
        Imagecounter = files.Length;
        MessageBox.Show(Imagecounter.ToString());
        counter = 0;
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        counter++;
        _MainImageSource = new Uri(files[counter - 1], UriKind.Relative);
        if (counter == Imagecounter)
            {
                counter = 0;
            }
    }

Anyone know what I'm doing wrong ?

Updated code

XAML

 <Image x:Name="Picture" Source="{Binding MainImageSource}"  Width="980" Height="760" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="350,50,0,0"></Image>

C#

public partial class IntroScreen : UserControl, INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private string[] files;
    private System.Timers.Timer timer;

    private int counter;
    private int Imagecounter;

    Uri _MainImageSource = null;

    public Uri MainImageSource
    {
        get 
        {
            return _MainImageSource; 
        } 
        set 
        {
            _MainImageSource = value;
            OnPropertyChanged("MainImageSource");
        } 
    }

    public IntroScreen()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(this.MainWindow_Loaded);
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {

        setupPics();
    }

    private void setupPics() 
    {
        files = Directory.GetFiles("../../Resources/Taken/", "*.jpg", SearchOption.TopDirectoryOnly);
        Imagecounter = files.Length;


        counter = 0;
        timer = new System.Timers.Timer();
        timer.Elapsed += new ElapsedEventHandler(timer_Tick);
        timer.Interval = (2000);
        timer.Enabled = true;
        timer.Start();


    }

    private void timer_Tick(object sender, EventArgs e)
    {
        counter++;
        MainImageSource = new Uri(files[counter - 1], UriKind.Relative);
        if (counter == Imagecounter)
            {
                counter = 0;
            }
    }

I'm not getting any error's but the image still isen't switching. I'm wondering if my paths are even working. Is there any way to test this ?

Arcade
  • 736
  • 2
  • 7
  • 17

2 Answers2

4

You have forgot to do notify the update to MainImageSource to the binding.

To do so, you have to implement the interface : INotifyPropertyChanged and define DataContext.

And, as written in the MSDN documentation "Setting Enabled to true is the same as calling Start, while setting Enabled to false is the same as calling Stop.".

Like this:

public partial class IntroScreen : Window, INotifyPropertyChanged
{
    private string[] files;
    private Timer timer;

    private int counter;
    private int Imagecounter;

    BitmapImage _MainImageSource = null;
    public BitmapImage MainImageSource  // Using Uri in the binding was no possible because the Source property of an Image is of type ImageSource. (Yes it is possible to write directly the path in the XAML to define the source, but it is a feature of XAML (called a TypeConverter), not WPF)
    {
        get
        {
            return _MainImageSource;
        }
        set
        {
            _MainImageSource = value;
            OnPropertyChanged("MainImageSource");  // Don't forget this line to notify WPF the value has changed.
        }
    }

    public IntroScreen()
    {
        InitializeComponent();
        DataContext = this;  // The DataContext allow WPF to know the initial object the binding is applied on. Here, in the Binding, you have written "Path=MainImageSource", OK, the "MainImageSource" of which object? Of the object defined by the DataContext.

        Loaded += MainWindow_Loaded;
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        setupPics();
    }

    private void setupPics()
    {
        timer = new Timer();
        timer.Elapsed += timer_Tick;
        timer.Interval = 2000;

        // Initialize "files", "Imagecounter", "counter" before starting the timer because the timer is not working in the same thread and it accesses these fields.
        files = Directory.GetFiles(@"../../Resources/Taken/", "*.jpg", SearchOption.TopDirectoryOnly);
        Imagecounter = files.Length;
        MessageBox.Show(Imagecounter.ToString());
        counter = 0;

        timer.Start();  // timer.Start() and timer.Enabled are equivalent, only one is necessary
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        // WPF requires all the function that modify (or even read sometimes) the visual interface to be called in a WPF dedicated thread.
        // IntroScreen() and MainWindow_Loaded(...) are executed by this thread
        // But, as I have said before, the Tick event of the Timer is called in another thread (a thread from the thread pool), then you can't directly modify the MainImageSource in this thread
        // Why? Because a modification of its value calls OnPropertyChanged that raise the event PropertyChanged that will try to update the Binding (that is directly linked with WPF)
        Dispatcher.Invoke(new Action(() =>  // Call a special portion of your code from the WPF thread (called dispatcher)
        {
            // Now that I have changed the type of MainImageSource, we have to load the bitmap ourselves.
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.UriSource = new Uri(files[counter], UriKind.Relative);
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;  // Don't know why. Found here (http://stackoverflow.com/questions/569561/dynamic-loading-of-images-in-wpf)
            bitmapImage.EndInit();
            MainImageSource = bitmapImage;  // Set the property (because if you set the field "_MainImageSource", there will be no call to OnPropertyChanged("MainImageSource"), then, no update of the binding.
        }));
        if (++counter == Imagecounter)
            counter = 0;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

And your XAML does not refer to the correct property:

<Grid>
    <Image x:Name="Picture" Source="{Binding MainImageSource}"  Width="980" Height="760" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="350,50,0,0"></Image>
<Grid>

Why do you need to implement INotifyPropertyChanged?

Basically, when you define a binding, WPF will check if the class that contains the corresponding property defines INotifyPropertyChanged. If so, it will subscribe to the event PropertyChanged of the class.

Cédric Bignon
  • 12,892
  • 3
  • 39
  • 51
  • Or use a DependencyProperty. – Matt Burland Jan 23 '13 at 20:30
  • 1
    Very important also to set the property, not the field: `MainImageSource = new Uri(...)`, instead of `_MainImageSource = new Uri(...)`. – Clemens Jan 23 '13 at 20:31
  • And bind to that property: `Source="{Binding MainImageSource}"`. – Clemens Jan 23 '13 at 20:31
  • 1
    And don't call `timer.Enabled = true` and `timer.Start()` at the same time. Both do the same, and one is enough. – Clemens Jan 23 '13 at 20:33
  • 2
    @MattBurland I think it is easier to begin with _INotifyPropertyChanged_. But yes, it is another (more WPF) solution. – Cédric Bignon Jan 23 '13 at 20:33
  • I implemented INotifyPropertyChanged as an interface, then I got an error saying "does not implement interface member 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged'" so I added "public event PropertyChangedEventHandler PropertyChanged;". Now I get a green line under it I'm not using the event. When I add the line "OnPropertyChanged("MainImageSource");" I get this error "The best overloaded method match for 'System.Windows.DependencyObject.OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs)' has some invalid arguments" and "cannot convert from 'string' – Arcade Jan 23 '13 at 20:41
  • 2
    You certainly have forgotten to write the _OnPropertyChanged_ method I have added at the end of the code. – Cédric Bignon Jan 23 '13 at 20:44
  • Ah thanks! if also tried editing your post instead of mine by mistake – Arcade Jan 23 '13 at 20:45
  • @Spedax I've rolled it back. Go ahead and edit your question. – Clemens Jan 23 '13 at 20:48
  • I'm not getting any error's but the image still isen't loading. I'm wondering if my paths are even working. Is there any way to test this ? updated code above – Arcade Jan 23 '13 at 20:56
  • 1
    I'm fixing the bug. But there are multiple small mistakes to fix. – Cédric Bignon Jan 23 '13 at 21:08
  • 1
    Now, the code works well on my computer. I will comment it to explain why we need all this stuff. – Cédric Bignon Jan 23 '13 at 21:12
  • Ow man, it works! Your my personal hero of the day! Learned ton of stuff and you saved me a couple of /rage quits. Thanks man :) – Arcade Jan 23 '13 at 21:18
  • 1
    Don't forget to read my modified post (when it will be modified) to learn plenty of new stuff ;) – Cédric Bignon Jan 23 '13 at 21:19
  • I'm making a usabilty video tomorrow, I'll upload it and post it here so you can see what you helped out with :) cheers – Arcade Jan 23 '13 at 22:39
2

I'm not seeing any use of the INotifyPropertyChanged interface, which would be required to update a UI item the way you are using it. As it is now, the UI control has no way of knowing that the value was updated.

Grant H.
  • 3,689
  • 2
  • 35
  • 53