Phan Khoa
Phan Khoa

Reputation: 13

How to dynamically change the color of an SVG in WPF (.NET Framework 4.8) on hover?

I am developing a WPF application using .NET Framework 4.8, and I need to display SVG icons that change color dynamically when hovered over.

Since .NET Framework 4.8 does not support SvgImageSource, I am looking for the best way to:

Load an SVG file in WPF Change the SVG color dynamically, e.g., when hovering over a button What are the best approaches to achieve this in .NET Framework 4.8?

Here is my current approach:

<Window.Resources>
    <!-- SVG icon -->
    <Geometry x:Key="SVGIcon">M 10,30 L 30,10 L 50,30 L 50,50 L 10,50 Z M 20,50 L 20,35 L 40,35 L 40,50 Z</Geometry>
</Window.Resources>

<Grid>
    <Button Margin="10" Width="50" Height="30" Background="Gray">
        <StackPanel Orientation="Horizontal">
            <Path Data="{StaticResource SVGIcon}" Width="14" Height="14" Stretch="Uniform">
                <Path.Style>
                    <Style TargetType="Path">
                        <Setter Property="Fill" Value="Orange"/>
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=IsMouseOver}" Value="True">
                                <Setter Property="Fill" Value="Red"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Path.Style>
            </Path>
        </StackPanel>
    </Button>
</Grid>

Upvotes: -2

Views: 79

Answers (0)

Related Questions