为什么MouseOver上的按钮颜色不变

时间:2019-10-18 11:18:07

标签: wpf xaml button colors mousehover

我不明白为什么这段代码不起作用。

当我将鼠标悬停在按钮颜色上时,它仍然是默认的颜色。

<Window>
    <Window.Resources>

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

    </Window.Resources>

    <Grid>
        <Button
            Width="144"
            Height="58"
            Margin="320,177,0,0"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Content="Button" 
            Style="{StaticResource hover}" />
    </Grid>
</Window>

screen

1 个答案:

答案 0 :(得分:0)

有必要修改ControlTemplate来激活IsMouseOver事件,如下所示:

<Button Width="144" Height="58" Margin="320,177,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Content="Button" >
                <Button.Style>
                    <Style TargetType="Button">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="Button">
                                    <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="1">
                                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                                    </Border>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Background" Value="Red"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </Button.Style>
            </Button>