Hi @杨岑 ,
Welcome to Microsoft Q&A!
When using Binding from code behind, it is equivalent to this code in XAML. So, the image can only be changed when the app is started, just like what I said in this thread.
<Image x:Name="image1" Source="/Assets/contrast-standard/theme-dark/dll.png"/>
We cannot set {Themeresource} markup extension
from code behind, it is recommended to use **ThemeResource
**in XAML.
If you need to set the image source from code behind, you can refer to the following code, use FrameworkElement.ActualThemeChanged Event, then modify the picture resources.
private void Page_Loaded(object sender, RoutedEventArgs e)
{
Page page = (Page)sender;
if (page.ActualTheme == ElementTheme.Light)
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.UriSource = new Uri(image1.BaseUri, "Assets/Images/Light-logo.png");
image1.Source = bitmapImage;
}
else if (page.ActualTheme == ElementTheme.Dark)
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.UriSource = new Uri(image1.BaseUri, "Assets/Images/Dark-logo.png");
image1.Source = bitmapImage;
}
}
private void Page_ActualThemeChanged(FrameworkElement sender, object args)
{
if(sender.ActualTheme== ElementTheme.Light)
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.UriSource = new Uri(image1.BaseUri, "Assets/Images/Light-logo.png");
image1.Source = bitmapImage;
}
else if(sender.ActualTheme == ElementTheme.Dark)
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.UriSource = new Uri(image1.BaseUri, "Assets/Images/Dark-logo.png");
image1.Source = bitmapImage;
}
}
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.