Recently I was trying to make it so that at a click of a button I could change the Foreground color of all HyperlinkButton’s in my application.
To do so I traversed through all styles in my App.xaml until I found the template for my HyperlinkButton. Once found, I removed the setter that contained the Foreground color and I then tried to replace it with a new Setter that contains the new Foreground color.
The following code shows how I was trying to do this:
foreach (DictionaryEntry obj in App.Current.Resources) { if(obj.Value.GetType() == typeof(Style)) { Style resourceStyle = (Style)obj.Value; if (resourceStyle.TargetType == typeof(HyperlinkButton)) { resourceStyle.Setters.RemoveAt(0); // the first one is the foreground color Setter s = new Setter(HyperlinkButton.ForegroundProperty, new SolidColorBrush(newColor)); resourceStyle.Setters.Add(s); break; } } }
The problem is once a Style has been applied to a live element it’s consider “sealed” and it’s setters cannot be modified. That is, the Style.IsSealed property is set to true. The result is when you run the code above you get the following exception thrown:
Error HRESULT E_FAIL has been returned from a call to a COM component.
To work around this problem all you have to do is copy and replace style with a style that contains the new color you want. The following code shows you how to accomplish this:
Style style = new Style(typeof(HyperlinkButton)); style.BasedOn = App.Current.Resources[typeof(HyperlinkButton)] as Style; style.Setters.Add(new Setter(HyperlinkButton.ForegroundProperty, new SolidColorBrush(color))); App.Current.Resources.Remove(typeof(HyperlinkButton)); App.Current.Resources.Add(typeof(HyperlinkButton), style);
Thanks to Jesse Bishop for showing me this technique!
–Mike






