如何知道何时从网络上加载一组图像?

时间:2013-03-04 18:47:33

标签: c# image events windows-8

我有一个视图,可以将1到5个图像(取决于从服务器接收的数据)提取到StackPanel,现在只要下载它们(按任意顺序),它们就会弹出视图。我想隐藏所有图像,直到它们全部可用于渲染(即,当它们全部从网上加载并准备好显示时)。

现在,每张图片都有Loaded - 我可以听的事件。但是,跟踪一组真/假值并不断轮询这听起来像是一个坏主意。有没有更好的方法来完成我追求的目标?

1 个答案:

答案 0 :(得分:2)

不确定。假设您展示了许多不同的图像:

<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();
    }
}

我希望这会有所帮助。