【问题标题】:Changing background image based on localsettings根据本地设置更改背景图像
【发布时间】:2014-06-20 11:35:51
【问题描述】:

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

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

如果用户选择另一个主题,现在我希望更改背景图像,例如:

if(localSettings.Values["theme"].ToString() == "Dark"){
    //set ImageSource="Assets/BackgroundDark.png"
}

我该怎么办?

【问题讨论】:

    标签: c# xaml winrt-xaml windows-phone-8.1


    【解决方案1】:

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

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

    编辑:如果您希望根据一些自定义本地设置值更改值,您可能想试试这个:

    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;
    

    【讨论】:

    • 将这些行放在哪里?在公共 App() 中,它说是灾难性的失败
    • (使用绝对 uri,使用相对 uri 表示“给定的 System.Uri 无法转换为 Windows.Foundation.Uri。”)
    • 在 onlaunched 或 onactiveted 中,没有任何反应
    • @the_nuts 试试“ms-appx:/Assets/BackgroundDark.png”
    • 我知道这是旧的,但我收到错误“在 App.xaml 中使用此确切代码在类型“ResourceDictionary”中找不到可附加属性“ThemeDictionary”。任何想法为什么?
    【解决方案2】:

    如果你只是想根据当前主题选择na图像,你可以使用“主题”限定符。

    在您的情况下,您可以将图像的路径维护到“Assets/Background.png”,并在该目录中包含“Assets/Background.theme-dark.png”和“Assets/Background.theme-light.png”。每一个都将根据当前使用的主题进行选择。以编程方式,您可以通过调用来检查它:

    App.Current.RequestedTheme
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 2015-12-31
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      相关资源
      最近更新 更多