如何知道一组图像何时从web加载
本文关键字:何时 图像 web 加载 一组 何知道 | 更新日期: 2023-09-27 18:02:04
我有一个视图,它将1到5张图像(取决于从服务器接收到的数据)获取到StackPanel
中,现在它们只是在下载时(以任意随机顺序)弹出到视图中。我想隐藏所有的图像,直到它们都可用于渲染(即当它们都从网络加载并准备显示)。
现在,每个图像都有一个我可以侦听的Loaded
-事件。然而,跟踪true/false值数组并不断轮询这听起来不是个好主意。有没有更好的方法来实现我所追求的?
当然。假设你像这样展示你的许多不同的图像:
<Grid Background="Black">
<StackPanel x:Name="ImageContainer" Opacity="0" Width="100">
<Image Loaded="Image_Loaded_1" Source="http://www.hdwallpaperspk.com/wp-content/uploads/2013/01/1600x1200_hd_wallpaper_177.jpg" />
<Image Loaded="Image_Loaded_1" Source="http://www.hdwallpaperspk.com/wp-content/uploads/2013/01/nature-wallpaper-hd1.jpg" />
<Image Loaded="Image_Loaded_1" Source="http://hidefwalls.com/wp-content/g/hd-2/hd-wallpaper-30.jpg" />
<Image Loaded="Image_Loaded_1" Source="http://beautifulcoolwallpapers.files.wordpress.com/2011/09/red-tree-wallpaper-hd.jpg" />
<Image Loaded="Image_Loaded_1" Source="http://hidefwalls.com/wp-content/g/hd-2/at-the-beach-hd-wallpaper-1920x1200.jpg" />
<Image Loaded="Image_Loaded_1" Source="http://freedomwallpaper.com/wallpaper/funky-wallpaper-hd.jpg" />
<Image Loaded="Image_Loaded_1" Source="http://walfast.com/wp-content/uploads/2013/02/wallpaper-hd.jpg" />
<Image Loaded="Image_Loaded_1" Source="http://www.hdwallpaperspk.com/wp-content/uploads/2013/01/hd-wallpaper-6-o-u-ibackgroundz-com_.jpg" />
<Image Loaded="Image_Loaded_1" Source="http://2.bp.blogspot.com/-dcgYv-SFEu0/TZVuveCkq1I/AAAAAAAAI2A/vK0PXUJ8aKw/s1600/tiger_wallpapers_hd_Bengal_Tiger_hd_wallpaper.jpg" />
</StackPanel>
</Grid>
然后你可以隐藏它们,直到它们都被加载,像这样:
object m_ImagesLock = new object();
private List<Image> m_ImagesLoading = new List<Image>();
private void Image_Loaded_1(object sender, RoutedEventArgs e)
{
lock (m_ImagesLock)
{
var _Image = sender as Image;
m_ImagesLoading.Add(_Image);
var _Action = new Action(() =>
{
m_ImagesLoading.Remove(_Image);
ImageContainer.Opacity = m_ImagesLoading.Any() ? 0 : 1;
});
_Image.ImageOpened += (s, arg) => _Action();
_Image.ImageFailed += (s, arg) => _Action();
}
}