tags:

views:

40

answers:

5

Hello:

I have several HierarchicalDataTemplates in my TreeView. In one of them I would like to display an image to the right of the label if a property in this case HasMissingFit is true, otherwise the image should not be displayed at all.

If I wanted the image to always be present I know I could do this using just an Image tag with a converter, but again if the property is false, the image shouldn't be displayed at all.

+2  A: 

Easiest way is probably to just bind the Visibility-Property of the Image to HasMissingFit, using a Converter to translate true to Visible and false to Hidden (or Collapsed if you want use that space for something else). If you want the Image to be really not present, you need to create a trigger in some parent of the image. Define a ContentControl with a custom style, and in the style define a trigger, that sets your image as Content if HasMissingFit==True.

Simpzon
+1  A: 

There are a few options I can think of:

  1. You can bind this property to the image's Visibility. In this case, the image exists but is not drawn to the screen.
  2. You can create a DataTemplateSelector that selects the correct DataTemplate based on this property.
siz
A: 

The first thing that came to mind for me is to use an Image, bound to a property that returns either the image you want if the other property is set, or null otherwise.

This makes it easily extensible, in case you decide later to have different icons for different properties.

In code-behind:

public ImageSource MyImage
{
    get
    {
        if (this.IsImageFit)
            return .....;   // return an ImageSource using your image
        else
            return null;
    }
}
Wonko the Sane
+1  A: 

Related to the converter on collapsed/visible of an image, you could alternatively do a converter that converts true to your imagesource, or false to null

John Gardner
+2  A: 

You certainly don't need to code up a value converter or a template selector: just set the Image's Visibility to Collapsed and then attach a style to the Image that uses a DataTrigger, e.g.:

<Style TargetType="Image">       
   <Style.Triggers>
      <DataTrigger Binding="{Binding HasMissingFit}" Value="True">
         <DataTrigger.Setters>
            <Setter Property="Visibility" Value="Visible"/>
         </DataTrigger.Setters>
      </DataTrigger>
   </Style.Triggers>
</Style>

Depending on your layout, it may make more sense to set the Visibility to Hidden than Collapsed; that way, the image appearing or disappearing won't affect the flow of the layout.

Robert Rossney