2012-04-08 132 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