Home > database >  How to change color of an image button when the mouse is over it?
How to change color of an image button when the mouse is over it?

Time:04-06

I have created a Button with an image that you can see below:

Button with gear image.

I used the following XAML code to create this Button:

<Button Grid.Column="3" Style="{StaticResource MaterialDesignFlatButton}" Padding="0"
        ToolTip="Settings" Width="30"
        IsEnabled="{Binding DataContext.ControlsEnabled, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}">
    <materialDesign:PackIcon Kind="Cog" Width="32" Height="32" VerticalAlignment="Center" HorizontalAlignment="Center">
        <materialDesign:PackIcon.Style>
            <Style TargetType="materialDesign:PackIcon">
                <Setter Property="Foreground" Value="WhiteSmoke" />
                <Setter Property="Opacity" Value="0.7" />
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Foreground" Value="White" />
                        <Setter Property="Opacity" Value="1" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </materialDesign:PackIcon.Style>
    </materialDesign:PackIcon>
</Button>

My problem is that the icon color is changed only when the mouse is over the icon, not the Button. I want it to change color when the mouse is over the Button.

How can I fix it in my code?

CodePudding user response:

You can use a RelativeSource binding to refer to the IsMouseOver property of the parent Button.

<Style.Triggers>
   <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType={x:Type Button}}}" Value="True">
      <Setter Property="Foreground" Value="White" />
      <Setter Property="Opacity" Value="1" />
   </DataTrigger>
</Style.Triggers>
  • Related