0

I am trying to set a property of an element using DataTrigger in a style.

<Image x:Name="post_image1" Height="278" HorizontalAlignment="Left" VerticalAlignment="Top" Source="{Binding LatestFeed[1].PostImageURL}" MaxWidth="410" MaxHeight="410" Margin="0,0,50,0">
                            <Image.Style>
                                <Style>
                                    <Style.Triggers>
                                        <DataTrigger
                                              Binding="{Binding post_image1.Source}"
                                              Value="noimage">
                                            <Setter  Property="Image.Visibility" Value="Collapsed" />
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Image.Style>
                        </Image>

What I want to happen is that if the Source Value is set to "noimage" (which I am setting as part of my data object) the Image Visibility property is set to Collapsed.

I think I'm close, and I'm not sure what I'm missing.

discorax
  • 1,487
  • 4
  • 24
  • 39

1 Answers1

1

Since your Style is applied directly to the Image, the Bindings in the DataTrigger use the Current Image's DataContext, so you can reference the value the exact same way that you did in the Source binding.

<Image x:Name="post_image1" Height="278" HorizontalAlignment="Left" VerticalAlignment="Top" Source="{Binding LatestFeed[1].PostImageURL}" MaxWidth="410" MaxHeight="410" Margin="0,0,50,0">
    <Image.Style>
        <Style TargetType="{x:Type Image}">
             <Style.Triggers>
                 <DataTrigger
                     Binding="{Binding LatestFeed[1].PostImageURL}"
                     Value="noimage">
                         <Setter  Property="Visibility" Value="Collapsed" />
                 </DataTrigger>
             </Style.Triggers>
        </Style>
    </Image.Style>
</Image>
Rachel
  • 130,264
  • 66
  • 304
  • 490
  • ah, fantastic. That will work. As a side note, how would you path to a different element in the binding. For instance the DataTrigger would bind to the properly of another element entirely? – discorax Oct 03 '11 at 19:31
  • 1
    @discorax You could refer to an element by Name (`{Binding ElementName=post_image1, Path=Source}`), or you can use a RelativeSource binding which lets you look for a control relative to the current control (`{Binding RelativeSource={RelativeSource AncestorType={x:Type Image}}, Path=DataContext.LatestFeed[1]}` or `{Binding RelativeSource={RelativeSource Self}}`) – Rachel Oct 03 '11 at 19:49