Change the control style at runtime (Dynamic)

public static void LoadTheme(string xamlTheme)

        {

            if (string.IsNullOrEmpty(xamlTheme))

                return;

 

            ResourceDictionary resourceDictionary = XamlReader.Load(xamlTheme) as ResourceDictionary;

            string styleKey = string.Empty;

            Style applicationStyle = null;

 

            using (StringReader stream = new StringReader(xamlTheme))

            {

                using (XmlReader reader = XmlReader.Create(stream))

                {                   

                    while (reader.Read())

                    {

                        if (reader.NodeType == XmlNodeType.Element)

                        {

                            if (reader.Name == "Style")

                            {

                                styleKey = reader.GetAttribute("x:Key");

                                if (!string.IsNullOrEmpty(styleKey))

                                {

                                    applicationStyle = new Style();

                                    applicationStyle = (Style)resourceDictionary[styleKey];

                                    Application.Current.Resources.Remove(styleKey);

                                    Application.Current.Resources.Add(styleKey, applicationStyle);

                                }

                                else

                                {

                                    styleKey = reader.GetAttribute("x:Name");

                                    if (!string.IsNullOrEmpty(styleKey))

                                    {

                                        applicationStyle = new Style();

                                        applicationStyle = (Style)resourceDictionary[styleKey];

                                        Application.Current.Resources.Remove(styleKey);

                                        Application.Current.Resources.Add(styleKey, applicationStyle);

                                    }

                                }

                            }

                        }

                    }

                }

            }

        }

 

Comments