(using VS 2010) I’m new to WPF and am trying to create a TreeViewItem that displays 2 images, then some text. To do this I’m using StackPanel. I want the first image to show/hide depending upon changes to model property, so I added a trigger to set its width to 0:
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal" Margin="2" SnapsToDevicePixels="True" Width="Auto">
<Image Width="16" Height="16">
<Image.Style>
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<DataTrigger Binding="{Binding LinkType}" Value="Co">
<Setter Property="Source" Value="/Images/Image1.png"/>
</DataTrigger>
<DataTrigger Binding="{Binding LinkType}" Value="Post">
<Setter Property="Width" Value="0"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<Image Source="/Images/Image2.png"
Width="15"
Height="15"
SnapsToDevicePixels="True" Margin="3,0"/>
<TextBlock Text="{Binding Name}" Margin="5,0" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
This does in fact hide the image, but leaves an empty gap- the remaining items in the stackpanel do not slide to the left to account for the “removal” of the first image. I also tried triggering to Visibility with same results.
Is there a way I can add/remove, or show/hide, or change width=0, etc, items in StackPanel so that the remaining items readjust their positions accordingly? Or is there a better container than stackpanel for this?
Yes. When you are using a TreeView, the direct “children” of the TreeView are not actually your Image controls – your Image controls are contained within TreeViewItem controls. These are generated automatically and allow the TreeView to handle its children in a more intuitive way (without forcing all controls to implement the properties/functions required of a TreeView child).
It’s easy to customize these TeeViewItems. They share the same DataContext as your Images, so you can set the TreeView.ItemContainerStyle like so: