Net Us Up provides Silverlight Business Application Design, Development and Hosting Services. Contact us...

Read more...


Change a style in runtime using Silverlight. »

I was trying to complete a simple task today and got stuck.

The reason was that styles in Silverlight become sealed once they are set and trying to change a style in runtime just caused an error.
After doing some other things, it occured to me, that it may be possible to “copy” the style and add what I needed to it.

In my case, I had a custom control that I used for buttons (with some special behaviors) called AppButton, based on the Silverlight HyperlinkButton.
So a few experiments later I came up with this:

//Get the current style from the App.Resources
Style newStyle = new Style(typeof(AppButton));
newStyle.BasedOn = App.Current.Resources[typeof(AppButton)] as Style;

//Add the properties I need to change in the style
newStyle.Setters.Add(new Setter(AppButton.ForegroundProperty, new SolidColorBrush(Colors.Red)));

//Replace the original style with the newStyle
App.Current.Resources.Remove(typeof(AppButton));
App.Current.Resources.Add(typeof(AppButton), newStyle);

I’m not planning to use this alot, but it solved a problem I had, so I thought I should share.

Happy coding,
JW.