Switching between themes in WPF

When building an application you'd probably want to build themes and start changing the skin on specific controls. Sometimes users don't like the changes made - give them a choice, here's how.

Simply by creating a new style of the original, I've included two methods that will help achieve this -

  • SetDefaultStyle

This method will simply remove any styles associated with the textbox and set them all to the default style.

  • SetCustomStyle

Will do something similar as the method above, it will remove any styles set to existing textboxes and apply the custom style of myStyle

 Style myStyle = (Style) Application.Current.Resources["myStyleName"];
 
 public void SetDefaultStyle() {
 
     if (Application.Current.Resources.Contains(typeof(TextBox)))
     Application.Current.Resources.Remove(typeof(TextBox));
 
     Application.Current.Resources.Add(typeof(TextBox),
         new Style() {
            TargetType = typeof(TextBox)
        });
 }
 
 public void SetCustomStyle() {
     if (Application.Current.Resources.Contains(typeof(TextBox)))
     Application.Current.Resources.Remove(typeof(TextBox));
 
     Application.Current.Resources.Add(typeof(TextBox),
     myStyle);
 }

Sandeep Bansal
Salesforce Marketing Cloud Technical Architect
Follow me on LinkedIn

Comments

Powered by