根据本地设置更改背景图像

问题描述:

我在 App.xaml 中定义了每个页面背景,如下所示:

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"
}

我该怎么办?

您是否尝试过在 ThemeResource 中定义基于系统主题使用的 Dark 选项?

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>

如果您希望根据某些自定义本地设置值更改该值,您可能想尝试以下操作:

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;