简体   繁体   English

更改主题后更改背景图像

[英]Change Background Image when Theme has been changed

I'm trying to change the ImageSource of an ImageBrush when the user changes the theme of his phone in his settings. 当用户在其设置中更改手机主题时,我正在尝试更改ImageBrush的ImageSource。

So currently I have this: 所以目前我有这个:

XAML: XAML:

<ImageBrush ImageSource="{Binding ImageSource, Mode=OneTime}" Stretch="UniformToFill"/>

CodeBehind: 代码背后:

public string ImageSource
{
    get
    {
        if ((Visibility)App.Current.Resources["PhoneDarkThemeVisibility"]
            == Visibility.Visible)
        {
            return "/Images/BGDark.png";

        }
        else
        {
            return "/Images/BG.png";

        }
    }
    private set { }
}

As you can see, I'm setting the Background when the application has been started. 如您所见,启动应用程序时将设置背景。 The app will set the Background by seeing which Theme has been selected. 该应用程序将通过查看已选择哪个主题来设置背景。

My problem is now that when the user goes to settings (application hasn't been closed!) and changes the theme, the Background/ImageSource won't be updated, when he activates the app pagain. 我的问题现在是,当用户转到设置(尚未关闭应用程序!)并更改主题时,重新激活应用程序时,不会更新Background / ImageSource。 I've thought that maybe I could change it by setting the new Background here: 我以为也许可以通过在此处设置新背景来更改它:

App.xaml.cs: App.xaml.cs:

private void Application_Activated(object sender, ActivatedEventArgs e)
{
    //access somehow the CodeBehind of my MainPage and change the ImageSource
}

But I don't know how I would access the property... Is there maybe another solution to change the background while the app is still running and the user changes the theme? 但是我不知道我将如何访问该属性...在应用程序仍在运行并且用户更改主题时,是否可能存在另一种解决方案来更改背景?

You can try to put the logic in Page.OnNavigatedTo() instead of Application_Activated() : 您可以尝试将逻辑放在Page.OnNavigatedTo()中,而不是Application_Activated()

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    //do some logic to check if changing Background is necessary
    //if it is then change the Background, else simply return;
}

try this: 尝试这个:

Model class: 型号类别:

class SampleClass
{
    public string ImageSource
    {
        get
        {
            if ((Visibility)App.Current.Resources["PhoneDarkThemeVisibility"] == Visibility.Visible)
            {
                return "Dark";//You can set your Image here

            }
            else
            {
                return "Light";//You can set your Image here

            }
        }
        private set { }
    }
}

Usage : 用法:

private void Application_Activated(object sender, ActivatedEventArgs e)
{
    SampleClass obj = new SampleClass();
    Debug.WriteLine(obj.ImageSource);
}

NOTE : 注意 :

You are needed to mark tombstone upon deactivation while debugging as shown in Image. 如镜像所示, 在调试时需要在停用时标记墓碑 After doing it it would work as you are suppose to do 完成后,它会像您想的那样工作 调试时停用逻辑删除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM