应该使用 Uniform 来填充宽度而不是 UniformToFill (因为要填充的统一将尝试填充“高度”,并且由于没有定义高度,我可以看到它在回收项目时会导致问题)
也许您可以尝试限制同时加载的图像数量,例如以下代码将使用附加属性一次加载一个(您可以适应加载多个)。对于 AsyncLock,您可以使用此处的代码 (或在线搜索)
public static readonly DependencyProperty LimitedImageProperty = DependencyProperty.RegisterAttached("LimitedImage", typeof (string), typeof (LimitImageDownloadConverter), new PropertyMetadata(default(string),LimitedImagedChanged));
public static void SetLimitedImage(UIElement element, string value)
{
element.SetValue(LimitedImageProperty, value);
}
public static string GetLimitedImage(UIElement element)
{
return (string) element.GetValue(LimitedImageProperty);
}
AsyncLock imageLock = new AsyncLock();
private static async void LimitedImagedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Image currentImage = d as Image;
object dataContext = currentImage.DataContext;
string uri = e.NewValue as string;
if (string.IsNullOrEmpty(uri))
{
return;
}
using (await imageLock.AcquireLock())
{
if (currentImage.DataContext != dataContext)
{
//Item jhave been recycled
return;
}
await LoadImage(currentImage, uri);
}
}
private static Task<bool> LoadImage(Image image, string uri)
{
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
BitmapImage bitmap = new BitmapImage(new Uri(uri));
bitmap.ImageOpened += (send, arg) =>
{
tcs.SetResult(true);
};
bitmap.ImageFailed += (send, arg) =>
{
tcs.SetResult(false);
};
return tcs.Task;
}
然后只需使用local:MyAttatchedProperty.LimitedImage
在图像上设置图像源,而不是直接使用 ImageSource。