Home > other >  Change image color when app theme changed
Change image color when app theme changed

Time:02-25

I'm writing an app in UWP (C# & XAML). I have this code:

<Image Source="ms-appx:///Assets/Image.svg"/> <!-- svg is preferred but not required -->

Image.svg is single color (black) image. What I want to achieve is that the image changes color depending on the system/app theme (light theme = black image, dark theme = white image) without separated white and black image files.

At this moment, image is black.

Is it even possible?

I will appreciate any help and suggestion.

CodePudding user response:

Change image color when app theme changed

For your requirement, we suggest you use BitmapIcon to approach. And BitmapIcon has Foreground color property that you could set it dynamically when theme changed. And the other way is define different images for different themes, then binding image source with ThemeResource markup.

For example

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <BitmapIcon
        VerticalAlignment="Center"
        Foreground="{ThemeResource IconColor}"
        UriSource="ms-appx:///Assets/Butterfly.png"
        Visibility="Visible" />
    <Image
        Grid.Row="1"
        VerticalAlignment="Center"
        Source="{ThemeResource MyImage}" />

</Grid>

Resource

<ResourceDictionary.ThemeDictionaries>
    <ResourceDictionary x:Key="Light">
        <ImageSource x:Key="MyImage">ms-appx:///Assets/png-icon.png</ImageSource>

        <SolidColorBrush x:Key="IconColor" Color="Black" />
    </ResourceDictionary>

    <ResourceDictionary x:Key="Dark">
        <ImageSource x:Key="MyImage">ms-appx:///Assets/Butterfly.png</ImageSource>

        <SolidColorBrush x:Key="IconColor" Color="White" />
    </ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
  • Related