WPF - 如何在父项的鼠标悬停时更改子项的样式

时间:2013-04-15 04:57:40

标签: wpf xaml

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

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

enter image description here

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

这样做的简单风格结构是什么?

1 个答案:

答案 0 :(得分:24)

我不完全明白你需要什么,所以我发了2个样本。

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

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)当鼠标悬停在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>
相关问题