WPF图像源没有';t更新图像

本文关键字:图像 更新 WPF | 更新日期: 2023-09-27 18:28:39

我正试图在我的WPF应用程序中有一个旋转的广告显示。当我加载应用程序时,GetNewAd()方法会正确地显示广告。当我试图通过再次调用GetNewAd()方法来更新广告时,聊天主机会返回新广告,但UI中的图像不会更新。我尝试过在没有动画的情况下更新图像,但我仍然有同样的问题。我在这里错过了什么?

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

WPF图像源没有';t更新图像

如果调用GetNewAd()方法的计时器不是DispatcherTimer,则必须在UI线程中显式调用Image控件的Source属性的赋值:

image.Freeze(); // necessary for cross-thread access
imgAd.Dispatcher.BeginInvoke(new Action(() => imgAd.Source = image));