wpf的button设置鼠标经过时的背景色 IsMouseOver

发布时间 2023-07-22 21:49:59作者: 户的博客
IsMouseOver鼠标经过时,IsPressed鼠标点击时
<Style TargetType="{x:Type Button}">
    <Setter Property="Foreground" Value="White" />
    <Setter Property="Background" Value="Orange"/>
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="BorderBrush" Value="White" />
    <Setter Property="Margin" Value="5" />
    <Setter Property="Cursor" Value="Hand" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="White"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="BorderBrush" Value="Orange"/>
            <Setter Property="Foreground" Value="Orange" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="Background" Value="Orange"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="BorderBrush" Value="White" />
            <Setter Property="Foreground" Value="White" />
        </Trigger>
    </Style.Triggers>
</Style>
不知道为什么需要设置<Setter Property="Template">,但IsMouseOver想要修改border属性,必须在<Setter Property="Template">下的<Border>设置一下,另外如果这里的比如BorderBrush、BorderThickness固定的IsMouseOver再修改也不会变。


https://www.coder.work/article/6478093 记录了方法,没说为什么,另外这个网页上的链接 https://stackoverflow.com/questions/17259280/ 记录了另一个方法,没有测试