在父元素触发器中的子元素上设置 属性

Set a property on child element in trigger on parent element

我有一个网格,它由两行组成,第二行有一个矩形。每当鼠标悬停在网格上时,我想将其颜色更改为红色。

我尝试使用 EventTrigger,但是当鼠标悬停在网格上时没有任何反应

<Grid Width="50" Height="50" Background="Green">
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <Grid.Style>
        <Style TargetType="{x:Type Grid}">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Rectangle.Fill" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Grid.Style>

    <Rectangle Grid.Row="1" Fill="LightGray" />
</Grid>

Rectangle.Fill 不是 Grid 的 属性。将 Style 移动到要更改的元素:

<Grid Width="50" Height="50" Background="Green">
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>

    <Rectangle Grid.Row="1">
        <Rectangle.Style>
            <Style TargetType="Rectangle">
                <Setter Property="Fill" Value="LightGray" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=Grid}}"
                                 Value="True">
                        <Setter Property="Fill" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Rectangle.Style>
    </Rectangle>
</Grid>