Changing background image based on localsettings

我是研究僧i 提交于 2019-12-11 05:29:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!