2012-04-08 134 views
0

你可以看到这个标签:如何在DataTemplate上设置默认值?

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

回答

1

Style加上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> 

当心precedence本地值

+0

也许我错了,什么情况是..我使用的Windows8和VS2008在电网中的应用..它告诉我:附着式属性触发器不是在风格 – 2012-04-08 03:36:35

+0

发现您需要将'Style.Triggers'放置在* not *'Style'元素中,以便发生类似的错误,您确定您拥有正确的结构吗? 'Triggers'只是'Style'的一个普通属性,而不是[附件](http://msdn.microsoft.com/zh-cn/library/ms749011.aspx)。 – 2012-04-08 03:51:56

+0

嗯,正如我告诉你的,我使用的是VS 2011(不是2008,不好意思),而且我正在创建一个metro应用程序,可能这就是原因 – 2012-04-08 03:54:14

0

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

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

Microsoft FallbackValue Property