Switching between themes in WPF

When building applications 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.

Say you have a custom textbox style with the key name as "myCustomStyle" which completely changes the look of the textbox but your user wants it back to the original style. How do you go about being able to switch between the default Windows style and your beefed up custom style? 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 is a Software Engineer focusing on Microsoft and Web technologies. He looks to develop both well designed and functional desktop/phone applications.

Similar Posts you might like

Comments