用于ListBox项目的DataTemplate中的IsSelected的WPF触发器
我有一个列表框,我有以下的ItemTemplate:
<DataTemplate x:Key="ScenarioItemTemplate"> <Border Margin="5,0,5,0" Background="#FF3C3B3B" BorderBrush="#FF797878" BorderThickness="2" CornerRadius="5"> <DockPanel> <DockPanel DockPanel.Dock="Top" Margin="0,2,0,0"> <Button HorizontalAlignment="Left" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="White" /> <Label Content="{Binding Path=Name}" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="white" /> <Label HorizontalAlignment="Right" Background="#FF3C3B3B" Content="X" DockPanel.Dock="Left" FontWeight="Heavy" Foreground="White" /> </DockPanel> <ContentControl Name="designerContent" Visibility="Collapsed" MinHeight="100" Margin="2,0,2,2" Content="{Binding Path=DesignerInstance}" Background="#FF999898"> </ContentControl> </DockPanel> </Border> </DataTemplate>
正如你所看到的ContentControl的可见性设置为折叠。
我需要定义一个触发器,使可见性被设置为“可见”
当ListItem被选中,但我无法弄清楚。
有任何想法吗?
更新:当然,我可以简单地复制DataTemplate,并添加触发器到有问题的ListBox使用一个或另一个,但我想防止重复此代码。
您可以设置您的ContentControl样式,以便在选中容器(ListBoxItem)时激发触发器:
<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>
另外,我认为你可以将触发器添加到模板本身,并通过名称引用控件。 我不知道这种技术足够好,从内存中键入它,并假设它会工作,但它是这样的:
<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,谢谢!
只需要添加一个IsSelected == false的触发器,现在它就像一个魅力!
<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>