public Theme?GetTheme(ResourceDictionary resourceDictionary) { if (resourceDictionary is null) { throw new ArgumentNullException(nameof(resourceDictionary)); } var themeInstance = Theme.GetThemeInstance(resourceDictionary); if (themeInstance is not null) { return(themeInstance); } var builtInTheme = this.Themes.FirstOrDefault(x => x.Name == Theme.GetThemeName(resourceDictionary)); if (builtInTheme is not null) { return(builtInTheme); } // support dynamically created runtime resource dictionaries if (this.IsRuntimeGeneratedThemeDictionary(resourceDictionary)) { foreach (var resourceDictionaryKey in resourceDictionary.Keys) { if (Theme.ThemeInstanceKey.Equals(resourceDictionaryKey)) { return((Theme)resourceDictionary[resourceDictionaryKey]); } } foreach (var resourceDictionaryKey in resourceDictionary.Keys) { if (LibraryTheme.LibraryThemeInstanceKey.Equals(resourceDictionaryKey)) { var parentTheme = ((LibraryTheme)resourceDictionary[resourceDictionaryKey]).ParentTheme; if (parentTheme is not null) { return(parentTheme); } } } return(new Theme(new LibraryTheme(resourceDictionary, null))); } return(null); }
private Theme ChangeTheme(object?target, ResourceDictionary resourceDictionary, Theme?oldTheme, Theme newTheme) { if (resourceDictionary is null) { throw new ArgumentNullException(nameof(resourceDictionary)); } if (newTheme is null) { throw new ArgumentNullException(nameof(newTheme)); } var themeChanged = false; if (oldTheme != newTheme) { resourceDictionary.BeginInit(); try { ResourceDictionary? oldThemeDictionary = null; List <ResourceDictionary>?oldThemeResources = null; if (oldTheme is not null) { oldThemeDictionary = resourceDictionary.MergedDictionaries.FirstOrDefault(d => Theme.GetThemeInstance(d) == oldTheme); if (oldThemeDictionary is null) { oldThemeResources = resourceDictionary.MergedDictionaries.Where(d => Theme.GetThemeName(d) == oldTheme.Name) .ToList(); } } { newTheme.EnsureAllLibraryThemeProvidersProvided(); resourceDictionary.MergedDictionaries.Add(newTheme.Resources); //foreach (var themeResource in newTheme.GetAllResources()) //{ // // todo: Should we really append the theme resources or try to insert them at a specific index? // // The problem here would be to get the correct index. // // Inserting them at index 0 is not a good idea as user included resources, like generic.xaml, would be behind our resources. // //resourceDictionary.MergedDictionaries.Insert(0, themeResource); // resourceDictionary.MergedDictionaries.Add(themeResource); //} } if (oldThemeDictionary is not null) { resourceDictionary.MergedDictionaries.Remove(oldThemeDictionary); } else if (oldThemeResources is not null) { foreach (var themeResource in oldThemeResources) { resourceDictionary.MergedDictionaries.Remove(themeResource); } } themeChanged = true; } finally { resourceDictionary.EndInit(); } } if (themeChanged) { this.OnThemeChanged(target, resourceDictionary, oldTheme, newTheme); } return(newTheme); }