How to remove App.xaml ResourceDictionary at startup?

大兔子大兔子 提交于 2021-01-27 16:24:05

问题


I have a ResourceDictionary declared in the App.xaml file as below:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Skins/DefaultSkin.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

The problem is that when I attempt to load a different skin at start-up (using the App.xaml.cs constructor to load the last used ResourceDictionary skin) I find that the ResourceDictionary set in Application.Resources overrides this and reverts back to the DefaultSkin.xaml file - even when I use Application.Current.Resources.MergedDictionaries.Clear(); before choosing the required skin.

My app works perfectly when I remove the ResourceDictionary from Application.Resources - but then all xaml references are lost at design time. How can I keep this reference at design time but remove it at runtime before it can override my skin choice?


回答1:


Override the OnStartup method in App.xaml.cs:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        Resources.MergedDictionaries.Clear();
        //...
    }
}

If you want to clear MergedDictionaries in the constructor, you should do it after you have called InitializeComponent():

public App()
{
    InitializeComponent();
    Resources.MergedDictionaries.Clear();
}


来源:https://stackoverflow.com/questions/51420960/how-to-remove-app-xaml-resourcedictionary-at-startup

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