[英]WPF Image source doesn't update image
I'm trying to have a rotating ad display in my WPF application. 我正在尝试在我的WPF应用程序中显示旋转广告。 When I load the application the GetNewAd() method properly displays the advertisement.
当我加载应用程序时,GetNewAd()方法正确显示广告。 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.
当我尝试通过再次调用我的GetNewAd()方法来更新广告时,chatHost会返回新广告,但图片不会在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();
}
}
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: 如果调用
GetNewAd()
方法的计时器不是DispatcherTimer
,则显式必须在UI线程中调用Image控件的Source
属性的赋值:
image.Freeze(); // necessary for cross-thread access
imgAd.Dispatcher.BeginInvoke(new Action(() => imgAd.Source = image));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.