WPF Trigger for IsSelected in a DataTemplate for ListBox items
You can style your ContentControl such that a trigger fires when its container (the ListBoxItem) becomes selected:
<ContentControl x:Name="designerContent" MinHeight="100" Margin="2,0,2,2" Content="{Binding Path=DesignerInstance}" Background="#FF999898"> <ContentControl.Style> <Style TargetType="{x:Type ContentControl}"> <Setter Property="Visibility" Value="Collapsed"/> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True"> <Setter Property="Visibility" Value="Visible"/> </DataTrigger> </Style.Triggers> </Style> </ContentControl.Style></ContentControl>
Alternatively, I think you can add the trigger to the template itself and reference the control by name. I don't know this technique well enough to type it from memory and assume it'll work, but it's something like this:
<DataTemplate x:Key="ScenarioItemTemplate"> <DataTemplate.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Value="True"> <Setter TargetName="designerContent" Property="Visibility" Value="Visible"/> </DataTrigger> </DataTemplate.Triggers> ...</DataTemplate>
@Matt, Thank you!!!
Just had to add a trigger for IsSelected == false as well,and now it works like a charm!
<ContentControl.Style><Style TargetType="{x:Type ContentControl}"> <Setter Property="Visibility" Value="Collapsed"/> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}" Value="True"> <Setter Property="Visibility" Value="Visible"/> </DataTrigger> <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ListBoxItem}},Path=IsSelected}" Value="False"> <Setter Property="Visibility" Value="Collapsed"/> </DataTrigger> </Style.Triggers></Style>