WPF - 如何在触发器中访问子元素

4

我有一个像下面那样声明的ListBox。问题是,在项目定义中,我有很多带有网格和元素的内容。我想仅更改项目中一个图像的可见性,使其仅在选择该元素本身时可见。

我成功地更改了项目被选中时的背景和整体外观,但我无法访问内部元素 :(

<ListBox stuff stuff stuff>
    <ListBox.ItemTemplate>
        <DataTemplate DataType="local:Patient">
            <grids , borders, things, stuff
                <Image Name="image1" source opacity stuff/>
            </ grids bordes and design in general>
        </DataTemplate>
    </ListBox.ItemTemplate>

    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="Foreground" Value="White"/>
                    <!--HERE I WANT TO CHANGE VISIBILITY OF THE IMAGE-->
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>

    <ListBox.Template>
        <!-- some other styles when deselected and other things -->
    </ListBox.Template>
</ListBox>

我尝试使用:

<Setter TargetName="physiciansSettinsImage" Property="Visibility" Value="Visible"/>

但是不能在样式设置器上设置。有什么线索吗?

整个设计相当复杂,因此我希望尽可能避免重新编码。

1个回答

7

将触发器移动到 DataTemplate 中。

我猜想 image1VisibilityCollapsed

<DataTemplate.Triggers>
    <DataTrigger Binding="{Binding RelativeSource=
        {RelativeSource Mode=FindAncestor, AncestorType=
            {x:Type ListBoxItem}},Path=IsSelected}" Value="True">
        <Setter TargetName="image1" Property="Visibility" Value="Visible"/>
    </DataTrigger>
</DataTemplate.Triggers>

现在,当选中该项目时,您的图像可见性设置为可见。

太棒了,兄弟。快速而干净。我必须承认整个事情对我来说有点困惑,但是一步一步 :) - javirs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接