Traderman57
Traderman57

Reputation: 15

WPF Image source doesn't update image

I'm trying to have a rotating ad display in my WPF application. When I load the application the GetNewAd() method properly displays the advertisement. When I try to update the ad by calling my GetNewAd() method again, the chatHost is returning the new ad, but the image does not update in the UI. I have tried updating the image without the animation, but I still have the same problem. What am I missing here?

public class ncWindow
{                   
    public ncWindow(Grid grid)
    {           
        imgAd = new Image();
        imgAd.Margin = new Thickness(2,2,2,2);
        imgAd.HorizontalAlignment = HorizontalAlignment.Left;   
        imgAd.MouseDown += imgAd_MouseDown; 

        adTimer.Interval = 60000;
        adTimer.Elapsed += adTimer_Elapsed;
        adTimer.AutoReset = true;   
        adTimer.Start();

        grid.Children.Add(imgAd);       
    }                   

    public void GetNewAd()
    {
        DisplayedAd = chatHost.GetNewAd();

        debug.Print("GetNewAd: " + DisplayedAd.VendorName + ", ImageData.Length = " + DisplayedAd.ImageData.Length);

        BitmapImage image = new BitmapImage();
        if (DisplayedAd.ImageData!=null && DisplayedAd.ImageData.Length>0)
        {
            using (var mem = new MemoryStream(DisplayedAd.ImageData))
            {
                mem.Position = 0;               
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.StreamSource = mem;               
                image.EndInit();            
            }
        }   
        else
            return;

        image.Freeze();         
        imgAd.Source = image;
    }       

    private void adTimer_Elapsed(object source, ElapsedEventArgs e)
    {
        GetNewAd();
    }
}    

Upvotes: 1

Views: 5116

Answers (1)

Clemens
Clemens

Reputation: 128013

If the timer that calls your GetNewAd() method is not a DispatcherTimer, you'll explicitly have to invoke the assignment of the Image control's Source property in the UI thread:

image.Freeze(); // necessary for cross-thread access

imgAd.Dispatcher.BeginInvoke(new Action(() => imgAd.Source = image));

Upvotes: 3

Related Questions