【问题标题】:How to display default image until the original source images gets loaded如何在加载原始源图像之前显示默认图像
【发布时间】:2017-03-20 11:10:05
【问题描述】:

XAML 中,我在ItemControl DataTemplate 中有以下行。源pic 是从 c# 绑定到图像的。但是 pic 的加载需要一些时间。直到那时我想显示一些默认图像并在该 xaml 文件中加载其他 UI 元素。

<Image Grid.Row="0" Source="{Binding pic}" Stretch="Fill"  />

如何显示默认图片直到原始图片从图片 URL(url 到服务器)加载完成并在从 url 加载图片后将其替换为加载的图片?

Peter 的解决方案有效,但问题是我的应用程序在显示来自服务器 url 的图像之前挂起大约 10 秒。下面提到的代码

<ItemsControl x:Name="StoreCards" Margin="20" 
                      HorizontalAlignment="Center" VerticalAlignment="Top"
                      Grid.Row="2" AlternationCount="100000" >
            <ItemsControl.ItemTemplate>
                <DataTemplate>
  <Button BorderBrush="Black" Background="White" BorderThickness="0.2" Margin="10" Click="Card_Click">
                        <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                            <Rectangle Fill="Red" Stretch="UniformToFill"/>
                            <Image x:Name="BannerImage" Stretch="UniformToFill">
                                <Image.Source>
                                    <BitmapImage UriSource="{Binding pic, IsAsync="True"}"/>
                                </Image.Source>
                            </Image>
                     </Grid>
        </Button>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel ItemHeight="200" ItemWidth="300"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>

谢谢

【问题讨论】:

  • this answer,你大概可以在xaml中使用一些触发器来显示其他东西,直到图像被加载(或code-behind)。
  • 这是 DataTemplate 中的图像列表。我将 List 附加到 ItemSource ,其中包含 pic 作为一个键,它的值是图像链接。
  • 您应该绑定到一个 ImageLoader 类,该类将包含 DefaultImage 属性、Loaded 布尔属性和 ServerImage 属性。使用触发器,您可以将 DefaultImage 可见性绑定到 Loaded 属性,然后在您的视图模型中,您只需将 Loaded 属性更改为 true,一旦您从服务器加载图像,然后触发器将隐藏 DefaultImage 并显示 ServerImage。
  • 图片是从URI加载的,还是下载后创建ImageSource?在后一种情况下,您可能会使用 PriorityBinding。
  • Source="{Binding pic}" 在这里我将图片绑定到服务器 URI。它从 URI 加载

标签: c# wpf image xaml


【解决方案1】:

这并不漂亮,但却是最简单的方法。

假设您的占位符图像是Rectangle。 这是解决方案:

<Grid>
    <Rectangle Fill="Red" 
        Width="40"
        Height="40"
        />
    <Image 
        Stretch="Fill"
        Height="40"
        Width="40"
        Source="{Binding Path=pic, IsAsync=True}"
        />
</Grid>

当然,它会有 2 张图像的开销,但这样很容易!

【讨论】:

  • 是的,这行得通,但问题是我的应用在显示下载的图像之前会挂起大约 10 秒
  • 这是您实施的问题。您应该使用 asnyc-await-pattern。我用Source="{Binding Path=pic, IsAsync=True}" 展示了这个
  • 您的解决方案中有 IsAsync=True 正确。我用的一样
  • 提供如何加载图像伴侣的代码......我假设您在 ui 线程中同步加载它。然后当然一切都冻结或开始需要很长时间。 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
相关资源
最近更新 更多