Home > Net >  Set a property on child element in trigger on parent element
Set a property on child element in trigger on parent element

Time:10-26

I have a Grid which consists of two rows and a rectangle on the second row. I want to change its color to Red whenever the mouse is over the Grid.

What I tried using an EventTrigger, however nothing happens when the mouse hovers the Grid

<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>

enter image description here

CodePudding user response:

Rectangle.Fill is not a property of the Grid. Move the Style to the element being changed:

<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>
  • Related