C# WPF图像源没有';更新图像
我正在尝试在我的WPF应用程序中使用旋转广告显示。加载应用程序时,GetNewAd()方法会正确显示广告。当我再次调用GetNewAd()方法来更新广告时,chatHost会返回新广告,但图像不会在UI中更新。我尝试过在没有动画的情况下更新图像,但我仍然有同样的问题。我错过了什么C# WPF图像源没有';更新图像,c#,wpf,C#,Wpf,我正在尝试在我的WPF应用程序中使用旋转广告显示。加载应用程序时,GetNewAd()方法会正确显示广告。当我再次调用GetNewAd()方法来更新广告时,chatHost会返回新广告,但图像不会在UI中更新。我尝试过在没有动画的情况下更新图像,但我仍然有同样的问题。我错过了什么 public class ncWindow { public ncWindow(Grid grid) { imgAd = ne
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();
}
}
如果调用
GetNewAd()
方法的计时器不是dispatchermer
,则必须在UI线程中显式调用图像控件的Source
属性的赋值:
image.Freeze(); // necessary for cross-thread access
imgAd.Dispatcher.BeginInvoke(new Action(() => imgAd.Source = image));
imgAd
控件是否曾添加到UI中的面板中?它看起来不像。它被添加到网格中。我更新了代码以显示这是如何完成的。您确定DisplayedAd.ImageData始终为非零且不为空吗?UI线程中是否调用了GetNewAd方法?我添加了一个print语句来验证ImageData.Length始终为非零。正在从计时器调用GetNewAd()方法。我试图使示例代码尽可能简单。。。。它已经更新,以显示我如何使用计时器以及。