【问题标题】:When the Image is null, set another default image?当Image为null时,设置另一个默认图像?
【发布时间】:2012-04-21 01:12:35
【问题描述】:

你能看到这个标签吗:

<Image Source="{Binding Image}" Stretch="UniformToFill"/>

但是在下面呢?我想要做的是,当图像为空时,设置另一个默认图像。这可能吗?

<!-- Grid-appropriate 250 pixel square item template as seen in the GroupedItemsPage and ItemsPage -->
<DataTemplate x:Key="Standard250x250ItemTemplate">
    <Grid HorizontalAlignment="Left" Width="320" Height="240">
        <Border Background="{StaticResource ListViewItemPlaceholderRectBrush}">
            <Image Source="{Binding Image}" Stretch="UniformToFill"/>
        </Border>
        <StackPanel VerticalAlignment="Bottom" Background="{StaticResource ListViewItemOverlayBackgroundBrush}">
            <TextBlock Text="{Binding ShortTitle}" Foreground="{StaticResource ListViewItemOverlayTextBrush}" Style="{StaticResource TitleTextStyle}" Height="48" Margin="15,0,15,0"/>
        </StackPanel>
    </Grid>
</DataTemplate>

【问题讨论】:

    标签: c# wpf xaml styles datatemplate


    【解决方案1】:

    添加StyleDataTrigger。例如像

    <Image Stretch="UniformToFill">
         <Image.Style>
             <Style TargetType="Image">
                 <Setter Property="Source" Value="{Binding Image}"/>
                 <Style.Triggers>
                     <DataTrigger Binding="{Binding Image}" Value="{x:Null}">
                         <Setter Property="Source" Value="Images/Default.png"/>
                     </DataTrigger>
                 </Style.Triggers>
             </Style>
        </Image.Style>
    </Image>
    

    注意本地值precedence

    【讨论】:

    • 也许我错了,它发生了什么......我在网格应用程序中使用 Windows8 和 VS2008......它告诉我:在样式中找不到可附加属性触发器
    • 您需要将Style.Triggers 放在一个不是 Style 的元素中,这样才会发生这样的错误,你确定你有正确的结构吗? Triggers 只是 Style 的普通属性,而不是 attached 的属性。
    • 好吧,我告诉你,我使用的是 VS 2011(不是 2008,抱歉),因为我正在创建 Metro 应用程序,这可能就是原因
    • 不管你使用什么版本的 Visual Studio,问题是你可以使用什么样的 .NET 类。我不知道您在针对 Metro 应用程序时是否有这样的限制,但触发器从 .NET 3.0 开始就已经存在。
    • 我和@DarfZon 有同样的问题:我使用 Win8 和 VS12、.NET 4.5 并将您在上面发布的完全相同的代码复制到我的代码中并得到以下错误:“无法解析符号'触发器'”。谢谢。
    【解决方案2】:

    我不确定你是否需要一个触发器,当我需要在绑定值不会转换时指定一个值时,我通常会使用如下所示的后备值。

    <Image Source="{Binding Path=ImageURI, FallbackValue='SomeImageURI'}" />
    

    Microsoft FallbackValue Property

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 2019-06-13
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多