WPF - 如何在父母鼠标悬停时改变孩子的风格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16007923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 08:35:59  来源:igfitidea点击:

WPF - How to change children's style on mouseover of parent

wpfxaml

提问by Yisela

I have a StackPanel(1), with another StackPanel(2) inside.

我有一个StackPanel(1),StackPanel里面有另一个(2)。

SP 2 should be hidden (Opacity:0) until SP 1 is hovered. The mouse-over should change the style of SP2 to Opacity:100.

SP 2 应该隐藏(不透明度:0),直到 SP 1 悬停。鼠标悬停应该将 SP2 的样式更改为 Opacity:100。

enter image description here

在此处输入图片说明

I've tried defining styles in the StackPanel resources, and using triggers there to then target the inside panel, but I'm not sure how I should be targeting the children from inside the trigger.

我已经尝试在 StackPanel 资源中定义样式,然后在那里使用触发器来定位内部面板,但我不确定应该如何从触发器内部定位子项。

What would be a simple style structure to do this?

什么是简单的样式结构来做到这一点?

回答by Frank59

I do not fully understand what you need so i posted 2 samples.

我不完全了解您需要什么,所以我发布了 2 个样本。

Sample with colors for clarity :

为了清晰起见,带有颜色的样品:

1) when we have mouseover on sp1 sp2 getting green color

1)当我们将鼠标悬停在 sp1 sp2 上时,颜色变为绿色

<Window x:Class="Prognoz.GP.DataCollection.TestMarkupProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<Window.Resources>
    <Style x:Key="test" TargetType="StackPanel">
        <Setter Property="Background" Value="Red" />
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=StackPanel,AncestorLevel=1}, Path=IsMouseOver}" Value="True" >
                <Setter Property="Background" Value="Green" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Window.Resources>
<Grid>
    <StackPanel Width="400" Height="400" Background="Yellow">

        <StackPanel Width="350" Height="350" Style="{StaticResource test}"/>
    </StackPanel>
</Grid>
</Window>

2) when we have mouseover on sp2 sp2 getting green color

2)当我们将鼠标悬停在 sp2 sp2 上时,颜色变为绿色

<Style x:Key="test" TargetType="StackPanel">
        <Setter Property="Background" Value="Red" />
        <Style.Triggers>
            <Trigger Property="StackPanel.IsMouseOver" Value="True" >
                <Setter Property="Background" Value="Green" />
            </Trigger>
        </Style.Triggers>
</Style>