如何在 WPF Grid 中设置样式

How to set style at WPF Grid

我有这段代码并且有效:

<Grid Height="Auto" Width="Auto" HorizontalAlignment="Center"
    Margin="15,50,0,25" Grid.Row="8" MouseLeftButtonDown="buttonFermaNAO_Click">
<Image Margin="0,10,0,10"
      Width="206" Height="46" 
       HorizontalAlignment="Center">
    <Image.Style>
    <Style TargetType="{x:Type Image}">
        <Setter Property="Source" Value="./Resources/Tasto_esegui_senza scritta_ROLL_OFF.png"/>
        <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Source" Value="./Resources/Tasto start_senza scritta_Roll_ON.png"/>
        </Trigger>
        </Style.Triggers>
    </Style>
    </Image.Style>
</Image>
<Label HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Roboto-Bold"
   FontSize="25" Foreground="White" >Ferma NAO</Label>
</Grid>

使用此代码,当我将鼠标移到图像上时,图像发生了变化并且没问题,但是在图像的中心我有标签,我将鼠标移到标签上图像没有改变而且还不行。

我想如果可以删除图像代码并将样式设置为网格,这可能吗?

这是我现在的结果:

如果我将鼠标移到按钮上,我会得到:

您可以使用绑定到 Grids IsMouseOver 的 DataTrigger 来解决您的问题 属性:

<Grid Height="Auto" Width="Auto" HorizontalAlignment="Center"
Margin="15,50,0,25" Grid.Row="8" x:Name="myGrid" MouseLeftButtonDown="buttonFermaNAO_Click">
    <Image Margin="0,10,0,10"
  Width="206" Height="46" 
   HorizontalAlignment="Center">
        <Image.Style>
            <Style TargetType="{x:Type Image}">
                <Setter Property="Source" Value="./Resources/Tasto_esegui_senza scritta_ROLL_OFF.png"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver, ElementName=myGrid}" Value="True">
                        <Setter Property="Source" Value="./Resources/Tasto start_senza scritta_Roll_ON.png"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Image.Style>
    </Image>
    <Label HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Roboto-Bold"
      FontSize="25" Foreground="White" >Ferma NAO</Label>
</Grid>