Example #1
0
        private static Theme ChangeTheme(ResourceDictionary resources, Theme oldTheme, Theme newTheme)
        {
            var themeChanged = false;

            if (oldTheme != newTheme)
            {
                resources.BeginInit();

                ResourceDictionary oldThemeResource = null;
                if (oldTheme.IsNotNull())
                {
                    oldThemeResource = resources.MergedDictionaries.FirstOrDefault(d => AreResourceDictionarySourcesEqual(d, oldTheme.Resources));
                }

                resources.MergedDictionaries.Add(newTheme.Resources);

                if (oldThemeResource.IsNotNull())
                {
                    resources.MergedDictionaries.Remove(oldThemeResource);
                }

                themeChanged = true;
                resources.EndInit();
            }

            if (themeChanged)
            {
                OnThemeChanged(newTheme);
            }

            return(newTheme);
        }
Example #2
0
        /// <summary>
        ///     simple mvvm implementation
        /// </summary>
        private static ResourceDictionary RegisterMapping()
        {
            var resourceDictionary = new ResourceDictionary();

            resourceDictionary.BeginInit();

            var types = typeof(Program).Assembly.GetTypes().Where(x => !x.IsAbstract &&
                                                                  !x.IsNestedPrivate &&
                                                                  !x.IsInterface &&
                                                                  !x.IsEnum &&
                                                                  x.Namespace?.StartsWith("Calc.ViewModels") ==
                                                                  true)
                        .ToArray();
            var userControlType = typeof(UserControl);
            var viewTypes       = types.Where(x => userControlType.IsAssignableFrom(x));
            var modelTypes      = types.Except(viewTypes).ToArray();

            foreach (var modelType in modelTypes)
            {
                var viewName = modelType.Name + "View";
                var viewType = viewTypes.FirstOrDefault(x => x.Name == viewName)
                               ?? throw new Exception(
                                         $"View {viewName} not found for ViewModel {modelType}, ViewModels namespace only for ViewModels");
                var template = new DataTemplate(modelType);
                var root     = new FrameworkElementFactory(viewType);
                template.VisualTree = root;
                root.AddHandler(FrameworkElement.LoadedEvent, new RoutedEventHandler(Loaded));
                resourceDictionary.Add(template.DataTemplateKey, template);
                template.Seal();
            }

            resourceDictionary.EndInit();
            return(resourceDictionary);
        }
Example #3
0
        /// <summary>
        /// Set the current theme
        /// </summary>
        /// <param name="name">The name of the theme</param>
        /// <returns>true if the new theme is set, false otherwise</returns>
        public bool SetCurrent(string name)
        {
            if (ThemeDictionary.ContainsKey(name))
            {
                ITheme newTheme = ThemeDictionary[name];
                CurrentTheme = newTheme;

                ResourceDictionary theme    = Application.Current.MainWindow.Resources.MergedDictionaries[0];
                ResourceDictionary appTheme = Application.Current.Resources.MergedDictionaries.Count > 0
                                                  ? Application.Current.Resources.MergedDictionaries[0]
                                                  : null;
                theme.BeginInit();
                theme.MergedDictionaries.Clear();
                if (appTheme != null)
                {
                    appTheme.BeginInit();
                    appTheme.MergedDictionaries.Clear();
                }
                else
                {
                    appTheme = new ResourceDictionary();
                    appTheme.BeginInit();
                    Application.Current.Resources.MergedDictionaries.Add(appTheme);
                }
                foreach (Uri uri in newTheme.UriList)
                {
                    try
                    {
                        ResourceDictionary newDict = new ResourceDictionary {
                            Source = uri
                        };

                        /*AvalonDock and menu style needs to move to the application
                         * 1. AvalonDock needs global styles as floatable windows can be created
                         * 2. Menu's need global style as context menu can be created
                         */
                        if (uri.ToString().Contains("AvalonDock") ||
                            uri.ToString().Contains("Mjolnir.IDE.Core;component/Styles/VS2013/Menu.xaml"))
                        {
                            appTheme.MergedDictionaries.Add(newDict);
                        }
                        else
                        {
                            theme.MergedDictionaries.Add(newDict);
                        }
                    }
                    catch (Exception ex)
                    {
                        //TODO : Log error
                        Debugger.Break();
                    }
                }
                appTheme.EndInit();
                theme.EndInit();
                _logger.LogOutput(new LogOutputItem("Theme set to " + name, OutputCategory.Info, OutputPriority.None));
                _eventAggregator.GetEvent <ThemeChangeEvent>().Publish(newTheme);
            }
            return(false);
        }
Example #4
0
        /// <summary>
        /// Set the current theme
        /// </summary>
        /// <param name="name">The name of the theme</param>
        /// <returns>true if the new theme is set, false otherwise</returns>
        public bool SetCurrent(string name)
        {
            #if WINDOWS_APP
            if (ThemeDictionary.ContainsKey(name))
            {
                ITheme newTheme = ThemeDictionary[name];
                CurrentTheme = newTheme;

                //   ResourceDictionary theme = Application.Current.MainWindow.Resources.MergedDictionaries[0];
                ResourceDictionary appTheme = Application.Current.Resources.MergedDictionaries.Count > 0
                                                  ? Application.Current.Resources.MergedDictionaries[0]
                                                  : null;
                //  theme.BeginInit();
                //   theme.MergedDictionaries.Clear();
                if (appTheme != null)
                {
                    appTheme.BeginInit();
                    appTheme.MergedDictionaries.Clear();
                }
                else
                {
                    appTheme = new ResourceDictionary();
                    appTheme.BeginInit();
                    Application.Current.Resources.MergedDictionaries.Add(appTheme);
                }

                foreach (Uri uri in newTheme.UriList)
                {
                    ResourceDictionary newDict = new ResourceDictionary {
                        Source = uri
                    };

                    /*AvalonDock and menu style needs to move to the application
                     * 1. AvalonDock needs global styles as floatable windows can be created
                     * 2. Menu's need global style as context menu can be created
                     */
                    //if (uri.ToString().Contains("AvalonDock") ||
                    //    uri.ToString().Contains("Wide;component/Interfaces/Styles/VS2012/Menu.xaml"))
                    //{
                    appTheme.MergedDictionaries.Add(newDict);
                    //}
                    //else
                    //{
                    //    theme.MergedDictionaries.Add(newDict);
                    //}
                }
                appTheme.EndInit();

                //set Avalondock theme
                //todo in wpf dll       m_workspace.ADTheme = newTheme.ADTheme;

                //    theme.EndInit();
                _logger.Log("Theme set to " + name, LogCategory.Info, LogPriority.None);
                //todo         _eventAggregator.Publish<ThemeChangeEvent>()(newTheme);
            }
#endif
            return(false);
        }
Example #5
0
        // Behaviors
        public bool SetCurrentTheme(string name)
        {
            var theme = Themes.FirstOrDefault(t => t.Name == name);

            if (theme == null)
            {
                return(false);
            }

            CurrentTheme = theme;

            // add resource dictionary if not exist
            if (_applicationResourceDictionary == null)
            {
                _applicationResourceDictionary = new ResourceDictionary();
                Application.Current.Resources.MergedDictionaries.Add(_applicationResourceDictionary);
            }

            // begin update application and window resources
            _applicationResourceDictionary.BeginInit();
            _applicationResourceDictionary.MergedDictionaries.Clear();

            // get window resource dictionary
            var windowResourceDictionary = Application.Current.MainWindow.Resources.MergedDictionaries[0];

            windowResourceDictionary.BeginInit();
            windowResourceDictionary.MergedDictionaries.Clear();

            // load theme application resources
            foreach (var uri in theme.ApplicationResources)
            {
                _applicationResourceDictionary.MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = uri
                });
            }

            // load main window resources
            foreach (var uri in theme.MainWindowResources)
            {
                windowResourceDictionary.MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = uri
                });
            }

            // finish update
            _applicationResourceDictionary.EndInit();
            windowResourceDictionary.EndInit();

            // raise changed event
            CurrentThemeChanged?.Invoke(this, EventArgs.Empty);

            return(true);
        }
Example #6
0
        public bool SetCurrentTheme(string name)
        {
            var theme = _themes.FirstOrDefault(x => x.Name == name);

            if (theme == null)
            {
                return(false);
            }

            var mainWindow = Application.Current.MainWindow;

            if (mainWindow == null)
            {
                return(false);
            }

            CurrentTheme = theme;

            if (_applicationResourceDictionary == null)
            {
                _applicationResourceDictionary = new ResourceDictionary();
                Application.Current.Resources.MergedDictionaries.Add(_applicationResourceDictionary);
            }
            _applicationResourceDictionary.BeginInit();
            _applicationResourceDictionary.MergedDictionaries.Clear();

            var windowResourceDictionary = mainWindow.Resources.MergedDictionaries[0];

            windowResourceDictionary.BeginInit();
            windowResourceDictionary.MergedDictionaries.Clear();

            foreach (var uri in theme.ApplicationResources)
            {
                _applicationResourceDictionary.MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = uri
                });
            }

            foreach (var uri in theme.MainWindowResources)
            {
                windowResourceDictionary.MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = uri
                });
            }

            _applicationResourceDictionary.EndInit();
            windowResourceDictionary.EndInit();

            RaiseCurrentThemeChanged(EventArgs.Empty);

            return(true);
        }
Example #7
0
        protected override void OnStartup(StartupEventArgs e)
        {
            // Ensure that only one instance of the application can run at any time
            if (e.Args.Any(a => a == Constants.IgnoreMutexFlag))
            {
                if (!SingleInstance.Start())
                {
                    SingleInstance.ShowFirstInstance();
                    Shutdown(0);
                    return;
                }
            }

            ConfigureLogging();
            LogTo.Info("Application start");
            LogEnvironmentInfo();

            DispatcherHelper.Initialize();
            ProxyServer.Start(Kernel.Get <ITwitterContextList>());

            Scheduler = Kernel.Get <IScheduler>();
            Scheduler.Start();

            base.OnStartup(e);

            CentralHandler = new CentralMessageHandler(Kernel);

            var conf    = Kernel.Get <IConfig>();
            var palette = new PaletteHelper();

            palette.SetLightDark(conf.Visual.UseDarkTheme);
            palette.ReplaceAccentColor(conf.Visual.AccentColor);
            palette.ReplacePrimaryColor(conf.Visual.PrimaryColor);

            var swatches = new SwatchesProvider().Swatches.ToArray();

            var resDict = new ResourceDictionary();

            resDict.BeginInit();
            {
                resDict.Add("HashtagBrush",
                            new SolidColorBrush(swatches.First(s => s.Name == conf.Visual.HashtagColor).ExemplarHue.Color));
                resDict.Add("LinkBrush",
                            new SolidColorBrush(swatches.First(s => s.Name == conf.Visual.LinkColor).ExemplarHue.Color));
                resDict.Add("MentionBrush",
                            new SolidColorBrush(swatches.First(s => s.Name == conf.Visual.MentionColor).ExemplarHue.Color));
                resDict.Add("GlobalFontSize", (double)conf.Visual.FontSize);
            }
            resDict.EndInit();

            Resources.MergedDictionaries.Add(resDict);
            ChangeLanguage(conf);
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            long QQNum = (long)value;
            ResourceDictionary resource = new ResourceDictionary();

            resource.BeginInit();
            resource.Source = new Uri("/ChatHot.ControlLib;component/Themes/QQStyleResource.xaml", UriKind.Relative);
            resource.EndInit();
            //这里可以通过数据库将所有消息 Style 装进数据库,名称、详细信息、Key、需求等等
            //然后再一个数据库装关系 比如说2017922257 -> 1 表示2017922257用的ID为1的消息Style
            return(resource["MESSAGE_Style_ContentStyle_1"]);
        }
Example #9
0
 private static void ApplyResourceDictionary(ResourceDictionary newRd, ResourceDictionary oldRd)
 {
     oldRd.BeginInit();
     foreach (DictionaryEntry entry in newRd)
     {
         if (oldRd.Contains(entry.Key))
         {
             oldRd.Remove(entry.Key);
         }
         oldRd.Add(entry.Key, entry.Value);
     }
     oldRd.EndInit();
 }
Example #10
0
        private void OverrideFlyoutResources(ResourceDictionary resources, bool accent = false)
        {
            var fromColorKey = accent ? "MahApps.Colors.Highlight" : "MahApps.Colors.Flyout";

            resources.BeginInit();

            var fromColor = (Color)resources[fromColorKey];

            resources["MahApps.Colors.White"]  = fromColor;
            resources["MahApps.Colors.Flyout"] = fromColor;

            var newBrush = new SolidColorBrush(fromColor);

            newBrush.Freeze();
            resources["MahApps.Brushes.Flyout.Background"]  = newBrush;
            resources["MahApps.Brushes.Control.Background"] = newBrush;
            resources["MahApps.Brushes.White"]             = newBrush;
            resources["MahApps.Brushes.WhiteColor"]        = newBrush;
            resources["MahApps.Brushes.DisabledWhite"]     = newBrush;
            resources["MahApps.Brushes.Window.Background"] = newBrush;
            resources[SystemColors.WindowBrushKey]         = newBrush;

            if (accent)
            {
                fromColor = (Color)resources["MahApps.Colors.IdealForeground"];
                newBrush  = new SolidColorBrush(fromColor);
                newBrush.Freeze();
                resources["MahApps.Brushes.Flyout.Foreground"] = newBrush;
                resources["MahApps.Brushes.Text"]       = newBrush;
                resources["MahApps.Brushes.Label.Text"] = newBrush;

                if (resources.Contains("MahApps.Colors.AccentBase"))
                {
                    fromColor = (Color)resources["MahApps.Colors.AccentBase"];
                }
                else
                {
                    var accentColor = (Color)resources["MahApps.Colors.Accent"];
                    fromColor = Color.FromArgb(255, accentColor.R, accentColor.G, accentColor.B);
                }
                newBrush = new SolidColorBrush(fromColor);
                newBrush.Freeze();
                resources["MahApps.Colors.Highlight"]  = fromColor;
                resources["MahApps.Brushes.Highlight"] = newBrush; resources["MahApps.Brushes.Highlight"] = newBrush;
            }

            resources.EndInit();
        }
Example #11
0
        private void OverrideFlyoutResources(ResourceDictionary resources, bool accent = false)
        {
            var fromColorKey = accent ? "HighlightColor" : "FlyoutColor";

            resources.BeginInit();

            var fromColor = (Color)resources[fromColorKey];

            resources["WhiteColor"]  = fromColor;
            resources["FlyoutColor"] = fromColor;

            var newBrush = new SolidColorBrush(fromColor);

            newBrush.Freeze();
            resources["FlyoutBackgroundBrush"]     = newBrush;
            resources["ControlBackgroundBrush"]    = newBrush;
            resources["WhiteBrush"]                = newBrush;
            resources["WhiteColorBrush"]           = newBrush;
            resources["DisabledWhiteBrush"]        = newBrush;
            resources["WindowBackgroundBrush"]     = newBrush;
            resources[SystemColors.WindowBrushKey] = newBrush;

            if (accent)
            {
                fromColor = (Color)resources["IdealForegroundColor"];
                newBrush  = new SolidColorBrush(fromColor);
                newBrush.Freeze();
                resources["FlyoutForegroundBrush"] = newBrush;
                resources["TextBrush"]             = newBrush;
                resources["LabelTextBrush"]        = newBrush;

                if (resources.Contains("AccentBaseColor"))
                {
                    fromColor = (Color)resources["AccentBaseColor"];
                }
                else
                {
                    var accentColor = (Color)resources["AccentColor"];
                    fromColor = Color.FromArgb(255, accentColor.R, accentColor.G, accentColor.B);
                }
                newBrush = new SolidColorBrush(fromColor);
                newBrush.Freeze();
                resources["HighlightColor"] = fromColor;
                resources["HighlightBrush"] = newBrush;
            }

            resources.EndInit();
        }
Example #12
0
        public static void ReplaceDictionary(this ResourceDictionary resourceDictionary, Uri source, ResourceDictionary destination)
        {
            resourceDictionary.BeginInit();

            resourceDictionary.MergedDictionaries.Add(destination);

            ResourceDictionary?oldResourceDictionary = resourceDictionary.MergedDictionaries
                                                       .FirstOrDefault(x => x.Source == source);

            if (oldResourceDictionary != null)
            {
                resourceDictionary.MergedDictionaries.Remove(oldResourceDictionary);
            }

            resourceDictionary.EndInit();
        }
Example #13
0
        public ThemeInfo LoadStyles(string appname, string styleName, ResourceDictionary appDic)
        {
            string path;
            string fileName;

            GetFullPath(appname, styleName, out path, out fileName);

            try
            {
                var themeName = "";
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    ResourceDictionary dic = (ResourceDictionary)XamlReader.Load(fs);
                    if (!dic.Contains(THEME_PREFIX))
                    {
                        throw new ThemeException("A theme for MediaPoint needs to have a TextBlock marked with x:Name=\"Theme\" while the text should be the name of the theme.");
                    }
                    themeName = ((TextBlock)dic[THEME_PREFIX]).Text;
                    if (PerformInit)
                    {
                        appDic.BeginInit();
                    }
                    var theme = Application.Current.Resources.MergedDictionaries.FirstOrDefault(rd =>
                    {
                        return(rd.Contains(THEME_PREFIX));
                    });
                    if (theme != null)
                    {
                        appDic.MergedDictionaries.Remove(theme);
                    }
                    appDic.MergedDictionaries.Add(dic);
                    if (PerformInit)
                    {
                        appDic.EndInit();
                    }
                    CurrentStyleFolder = Path.Combine(path, @"Themes\" + styleName);

                    return(new ThemeInfo {
                        Name = themeName, Path = styleName
                    });
                }
            }
            catch (Exception ex)
            {
                throw new ThemeException("Style: " + styleName + " contains an invalid WPF ResourceDictionary.\r\n\r\n" + ex.Message + "\r\n\r\n" + ex.StackTrace);
            }
        }
        /// <summary>Makes an attempt to load the replacement resources. If failed - re-creates the replacement source</summary>
        private void TryLoadResources()
        {
            ResourceDictionary replacementDictionary = new ResourceDictionary();

            try
            {
                replacementDictionary.BeginInit();
                replacementDictionary.Source = new Uri(replacementSourceFullPath, UriKind.Absolute);
                replacementDictionary.EndInit();

                Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => { ReplaceAvailableResources(replacementDictionary); }), DispatcherPriority.Send);
            }
            catch (WebException)
            {
                Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => { RestoreReplacementDictionary(); }), DispatcherPriority.Send);
            }
        }
        /// <summary>
        /// Convert dictionary to resources
        /// </summary>
        /// <param name="brushes"></param>
        public void SetBrushes(IDictionary <String, SolidColorBrush> brushes)
        {
            ResourceDictionary appDict   = GetAppDictionary();
            ResourceDictionary themeDict = CurrentThemeDictionary;

            // Reset visuals
            // Setup app style
            appDict.BeginInit();
            themeDict.Clear();

            // Object type not known at this point
            foreach (String key in brushes.Keys)
            {
                themeDict[key] = brushes[key];
            }

            appDict.EndInit();
        }
Example #16
0
        private void ApplyResourceDictionary(ResourceDictionary oldRd, ResourceDictionary newRd)
        {
            if (oldRd is null)
            {
                throw new ArgumentNullException(nameof(oldRd));
            }

            if (newRd is null)
            {
                throw new ArgumentNullException(nameof(newRd));
            }

            oldRd.BeginInit();

            this.ApplyResourceDictionaryEntries(oldRd, newRd);

            oldRd.EndInit();
        }
Example #17
0
        protected override void OnStartup(StartupEventArgs e)
        {
            if (!SingleInstance.Start())
            {
                SingleInstance.ShowFirstInstance();
                Shutdown(0);
                return;
            }

            DispatcherHelper.Initialize();
            Kernel = new Kernel();

            base.OnStartup(e);
            ConfigureLogging();
            LogTo.Info("Application start");
            LogEnvironmentInfo();

            var conf    = Kernel.Get <IConfig>();
            var palette = new PaletteHelper();

            palette.SetLightDark(conf.Visual.UseDarkTheme);
            palette.ReplaceAccentColor(conf.Visual.AccentColor);
            palette.ReplacePrimaryColor(conf.Visual.PrimaryColor);

            var swatches = new SwatchesProvider().Swatches.ToArray();

            var resDict = new ResourceDictionary();

            resDict.BeginInit();
            {
                resDict.Add("HashtagBrush",
                            new SolidColorBrush(swatches.First(s => s.Name == conf.Visual.HashtagColor).ExemplarHue.Color));
                resDict.Add("LinkBrush",
                            new SolidColorBrush(swatches.First(s => s.Name == conf.Visual.LinkColor).ExemplarHue.Color));
                resDict.Add("MentionBrush",
                            new SolidColorBrush(swatches.First(s => s.Name == conf.Visual.MentionColor).ExemplarHue.Color));
                resDict.Add("GlobalFontSize", (double)conf.Visual.FontSize);
            }
            resDict.EndInit();

            Resources.MergedDictionaries.Add(resDict);

            ChangeLanguage(conf.General.Language);
        }
Example #18
0
            private void SetTheme(ResourceDictionary resources, ThemeType newTheme, ThemeType currentTheme)
            {
                if (currentTheme != newTheme)
                {
                    resources.BeginInit();

                    if (currentTheme != ThemeType.none)
                    {
                        RemoveExistingTheme(resources);
                    }

                    if (newTheme != ThemeType.none)
                    {
                        resources.MergedDictionaries.Add(newTheme == ThemeType.light ? lightTheme : darkTheme);
                    }

                    resources.EndInit();
                }
            }
Example #19
0
        public void SetLanguage(Lang newLanguage)
        {
            ResourceDictionary dict    = Application.Current.Resources;
            string             resname = "Interface.ru.xaml";

            switch (newLanguage)
            {
            case Lang.Russian:
                resname = "Interface.ru.xaml";
                break;

            case Lang.English:
                resname = "Interface.en.xaml";
                break;

            default:
                resname = "Interface.ru.xaml";
                break;
            }
            try
            {
                dict.BeginInit();
                int i = 0;
                for (i = 0; i < dict.MergedDictionaries.Count; i++)
                {
                    if (((System.Windows.ResourceDictionary)dict.MergedDictionaries[i]).Source.LocalPath.EndsWith(resname))
                    {
                        break;
                    }
                }
                if (i < dict.MergedDictionaries.Count)
                {
                    ResourceDictionary res = dict.MergedDictionaries[i];
                    dict.MergedDictionaries.Remove(dict.MergedDictionaries[i]);
                    dict.MergedDictionaries.Add(res);
                }
            }
            finally
            {
                dict.EndInit();
            }
        }
Example #20
0
        public static void ApplyLanguage(string language)
        {
            if (language == "en-US")
            {
                s_stringsDictionary.Source = new Uri(@"Resources\Strings.xaml", UriKind.Relative);
                return;
            }

            if (string.IsNullOrEmpty(language))
            {
                string path = $"{LanguagesDirectory}{Path.DirectorySeparatorChar}Strings.{CultureInfo.CurrentCulture.Name}.xaml";
                if (File.Exists(path))
                {
                    s_stringsDictionary.Source = new Uri(path, UriKind.Absolute);
                }
                else
                {
                    s_stringsDictionary.Source = new Uri(@"Resources\Strings.xaml", UriKind.Relative);
                }
                return;
            }

            foreach (string langPath in Directory.EnumerateFiles(LanguagesDirectory))
            {
                string   file   = Path.GetFileName(langPath);
                string[] tokens = file.Split('.');
                if (tokens.Length < 2)
                {
                    continue;
                }
                if (tokens[1].Contains(language))
                {
                    s_stringsDictionary.BeginInit();
                    s_stringsDictionary.Source = new Uri(langPath, UriKind.Absolute);
                    s_stringsDictionary.EndInit();
                    return;
                }
            }

            s_stringsDictionary.Source = new Uri(@"Resources\Strings.xaml", UriKind.Relative);
        }
        public static void ReplaceDictionary(this ResourceDictionary resourceDictionary, Uri source, Uri destination)
        {
            resourceDictionary.BeginInit();

            if (!resourceDictionary.MergedDictionaries.Any(x => x.Source == destination))
            {
                resourceDictionary.MergedDictionaries.Add(
                    new ResourceDictionary()
                {
                    Source = destination
                });
            }

            ResourceDictionary oldResourceDictionary = resourceDictionary.MergedDictionaries
                                                       .FirstOrDefault(x => x.Source == source);

            if (oldResourceDictionary != null)
            {
                resourceDictionary.MergedDictionaries.Remove(oldResourceDictionary);
            }

            resourceDictionary.EndInit();
        }
Example #22
0
        public static void SwitchLang(string lang)
        {
            if (!Languages.Contains(lang))
            {
                lang = "en";
            }

            var merged = Application.Current.Resources.MergedDictionaries;

            if (CurrentLangDict != null && merged.Contains(CurrentLangDict))
            {
                merged.Remove(CurrentLangDict);
            }

            var assemblyName = typeof(Lang).Assembly.GetName().Name;

            CurrentLangDict = new ResourceDictionary()
            {
                Source = new Uri($"pack://application:,,,/{assemblyName};component/Resources/Langs/{lang}.xaml")
            };
            merged.Add(CurrentLangDict);
            CurrentLangDict.BeginInit();
        }
Example #23
0
        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);
        }