问题
I define every page background in App.xaml, like this:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
<ImageBrush x:Key="BackgroundImage" ImageSource="Assets/Background.png" Stretch="UniformToFill" />
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
</ResourceDictionary>
</Application.Resources>
And now I wish to change the background image if the user select another theme, for example:
if(localSettings.Values["theme"].ToString() == "Dark"){
//set ImageSource="Assets/BackgroundDark.png"
}
How can I do?
回答1:
Have you tried this defining Dark option in ThemeResource which would be used based on System theme?
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Default">
<ImageBrush x:Key="BackgroundImage" ImageSource="Assets/Background.png" Stretch="UniformToFill" />
</ResourceDictionary>
<ResourceDictionary x:Key="Dark">
<ImageBrush x:Key="BackgroundImage" ImageSource="Assets/BackgroundDark.png" Stretch="UniformToFill" />
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
</ResourceDictionary>
</Application.Resources>
EDIT: If you're looking to change the value based on some custom local setting value, you might want to try this:
BitmapImage darkImage = new BitmapImage(new Uri("Assets/BackgroundDark.png", UriKind.Relative));
(App.Current.Resources["BackgroundImage"] as ImageBrush).ImageSource = darkImage;
// or page Resources, depending on where the resource dictionaries are defined
// (this.Resources["BackgroundImage"] as ImageBrush).ImageSource = darkImage;
回答2:
If you simply want to select na image according to the current theme, you can use the "theme" qualifier.
In your case, you can maintain the image's path to "Assets/Background.png" and on that directory have "Assets/Background.theme-dark.png" and "Assets/Background.theme-light.png". Each one will be selected according to the current theme being used. Programmatically you can check it just by calling:
App.Current.RequestedTheme
来源:https://stackoverflow.com/questions/24326363/changing-background-image-based-on-localsettings