Button Color WPF

2020-05-02 13:10发布

问题:

I'm trying to change my button color when the mouse is over it but it's not working (the button is still blue) and all examples I find go like I'm doing:

<Button.Style>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="#424242"/>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="#8BC34A"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Button.Style>

What am I doing wrong?

回答1:

You should use ControlTemplate for this purpose like this:

<Button.Style>
     <Style TargetType="{x:Type Button}">
          <Setter Property="Background" Value="#424242"/>
          <Setter Property="Template">
              <Setter.Value>
                  <ControlTemplate TargetType="{x:Type Button}">
                       <Border Background="{TemplateBinding Background}">
                          <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                      </Border>
                  </ControlTemplate>
              </Setter.Value>
         </Setter>
         <Style.Triggers>
             <Trigger Property="IsMouseOver" Value="True">
                 <Setter Property="Background" Value="#8BC34A"/>
             </Trigger>
           </Style.Triggers>
     </Style>
</Button.Style>


标签: c# wpf button