我有一个名为MyBook的UserControl
WPF应用程序,在Loaded上将触发后台线程以获取域对象列表,每个域对象都有一个到blob存储中托管的Azure映像的URL。
对于我回来的每个域对象,我添加了一个名为LazyImageControl
的自定义控件的新实例,该控件将在后台从Azure下载图像并在完成后渲染图像。
这很好用,但是当我向场景中添加第二个MyBook控件时,由于某种原因图像不加载,我无法弄清楚为什么会这样。
以下是LazyImageControl
public LazyImageControl()
{
InitializeComponent();
DataContextChanged += ContextHasChanged;
}
private void ContextHasChanged(object sender, DependencyPropertyChangedEventArgs e)
{
// Start a thread to download the bitmap...
_uiThreadDispatcher = Dispatcher.CurrentDispatcher;
new Thread(WorkerThread).Start(DataContext);
}
private void WorkerThread(object arg)
{
var imageUrlString = arg as string;
string url = imageUrlString;
var uriSource = new Uri(url);
BitmapImage bi;
if (uriSource.IsFile)
{
bi = new BitmapImage(uriSource);
bi.Freeze();
_uiThreadDispatcher.Invoke(DispatcherPriority.Send, new DispatcherOperationCallback(SetBitmap), bi);
}
else
{
bi = new BitmapImage();
// Start downloading the bitmap...
bi.BeginInit();
bi.UriSource = uriSource;
bi.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
bi.DownloadCompleted += DownloadCompleted;
bi.DownloadFailed += DownloadFailed;
bi.EndInit();
}
// Spin waiting for the bitmap to finish loading...
Dispatcher.Run();
}
private void DownloadFailed(object sender, ExceptionEventArgs e)
{
throw new NotImplementedException();
}
private void DownloadCompleted(object sender, EventArgs e)
{
// The bitmap has been downloaded. Freeze the BitmapImage
// instance so we can hand it back to the UI thread.
var bi = (BitmapImage)sender;
bi.Freeze();
// Hand the bitmap back to the UI thread.
_uiThreadDispatcher.Invoke(DispatcherPriority.Send, new DispatcherOperationCallback(SetBitmap), bi);
// Exit the loop we are spinning in...
Dispatcher.CurrentDispatcher.InvokeShutdown();
}
private object SetBitmap(object arg)
{
LazyImage.Source = (BitmapImage)arg;
return null;
}
所以问题是,在第一次WorkerThread运行正常后执行此操作,但我从未收到DownloadCompleted
或DownloadFailed
方法的回调,我不知道为什么......
有什么想法吗?
答案 0 :(得分:1)
不确定但是在设置应该触发图像加载的DownloadCompleted
之前,您应该尝试附加DownloadFailed
和BitmapImage.UriSource
事件处理程序,因此可能是它已加载在你的事件处理程序被附加之前(不是第一次因为加载需要一段时间但是然后图像被缓存并将立即加载)
另外:LazyImageControl
继承了哪个类,所以如果不是,我可以测试它吗?