如何在DataTemplate上设置默认值?

时间:2021-08-16 17:08:33

Can you see this tag:

你能看到这个标签:

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

But below? What I'm trying to do is, when the Image is null, set another default image. Is this possible?

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

<!-- 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>

2 个解决方案

#1


1  

Add a Style with a DataTrigger. e.g. something like

使用DataTrigger添加样式。例如就像是

<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>

Watch out for precedence of local values.

注意本地值的优先级。

#2


0  

I'm not sure that you need a trigger I typically use a fallback value like below when I need to specifiy a value when the bound value will not convert.

我不确定你是否需要触发器当我需要在绑定值不转换时指定一个值时,我通常会使用类似下面的回退值。

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

Microsoft FallbackValue Property

Microsoft FallbackValue属性

#1


1  

Add a Style with a DataTrigger. e.g. something like

使用DataTrigger添加样式。例如就像是

<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>

Watch out for precedence of local values.

注意本地值的优先级。

#2


0  

I'm not sure that you need a trigger I typically use a fallback value like below when I need to specifiy a value when the bound value will not convert.

我不确定你是否需要触发器当我需要在绑定值不转换时指定一个值时,我通常会使用类似下面的回退值。

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

Microsoft FallbackValue Property

Microsoft FallbackValue属性