How organize UWP image resources based on theme

杨岑 171 Reputation points
2024-04-13T08:00:10.4566667+00:00

According to this article (https://learn.microsoft.com/en-us/windows/uwp/app-resources/images-tailored-for-scale-theme-contrast), I organized images like below in my app:

\Assets\Images\contrast-standard\theme-dark
-code.png
\Assets\Images\contrast-standard\theme-light
-code.png

I expected the following XAML should work:

<Image Source="/Images/code.png"/>

But it shows nothing either in design mode or during runtime. What should I do to get UWP automatically find the correct image file?

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Junjie Zhu - MSFT 17,841 Reputation points Microsoft Vendor
    2024-04-15T06:07:04.07+00:00

    Hi @杨岑 ,

    Welcome to Microsoft Q&A!

    The path of your Source lacks Assets.

     <Image Source="ms-appx:///Assets/Images/code.png"/>
    

    And if the theme changes, the image will not take effect immediately. The image source can only be changed when the app is started, not while it's running. If you want to automatically change the image when UWP runs, it is recommended to use Themeresource.

     <Grid>
         <Grid.Resources>
                 <ResourceDictionary>
                     <ResourceDictionary.ThemeDictionaries>
                         <ResourceDictionary x:Key="Light">
                             <ImageSource x:Key="Logo">/Assets/Images/contrast-standard/theme-light/logo.png</ImageSource>
                         </ResourceDictionary>
                 <ResourceDictionary x:Key="Dark">
                     <ImageSource x:Key="Logo">/Assets/Images/contrast-standard/theme-dark/logo.png</ImageSource>
                 </ResourceDictionary>
             </ResourceDictionary.ThemeDictionaries>
             </ResourceDictionary>
         </Grid.Resources>
    
     
     <StackPanel>
         <Image Source="{ThemeResource Logo}" Height="500" Width="500"/>
     </StackPanel>
    </Grid>
    

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.