how do i change the icon color by hovering or clicking a button?

You can accomplish this with a custom Button Style and a Foreground binding on your icon. Here is an example using a Rectangle as a stand-in for the icon.

The custom style changes the Foreground brush on IsMouseOver and IsPressed.

The custom style also has a stripped down control template since you don’t need to see the button’s visual states.

The icon has a binding to the Foreground property of its parent Button.

Button Style

<Style x:Key="IconButtonStyle" BasedOn="{StaticResource {x:Type Button}}" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Foreground" Value="White" />
    <Setter Property="Height" Value="18" />
    <Setter Property="Width" Value="18" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border
                    Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}">
                    <ContentPresenter />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <DataTrigger
            Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsMouseOver}"
            Value="True">
            <Setter Property="Foreground" Value="Green" />
        </DataTrigger>
        <DataTrigger
            Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsPressed}"
            Value="True">
            <Setter Property="Foreground" Value="Red" />
        </DataTrigger>
    </Style.Triggers>
</Style>

Button with Icon (using a Rectangle as a stand-in)

<Button Style="{StaticResource IconButtonStyle}">
    <Rectangle
        Width="16"
        Height="16"
        Fill="{Binding RelativeSource={RelativeSource AncestorType={x:Type Button}}, Path=Foreground}"
        StrokeThickness="0" />
</Button>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top