0

I was wondering how to retrieve a particular setter from a style object in code-behind in silverlight.

I have a style S which is correctly loaded and applied to some object. Then during runtime i want to alter one particular setter of this style say its Background setter (Of course what i want is to alter the value of one particular setter).

To do so i looked at the Setters collection which is of type SetterBaseCollection and contains all setters of this style. So far so good. This collection seems to include all setters as they are defined in XAML but how to do i get access to them ?

When i iterate over this collection i am dealing with objects of type "Setter". But I don't know how to pick the one which contains the "Background" property.

// this works totally fine; the variable myStyle is getting the correct Style
myStyle = this.Resources["myStyle"] as Style;

// the myStyle.Setters collection seems to contain all setters of the style
foreach (Setter s in myStyle.Setters) {

   // so now what to do to get the setter that sets the Background property of my style ??

  // my naive approach did not work:
  if (s.Property.ToString().equals("Background")) {

      // do something
  }
}

(The Setter objects does have a Name attribute, which in fact is exactly what I want to accomplish a comparison with the string "Background" - and debugging offered that this attribute truly contains the string "Background". ... But it's a non-public attribute!

It would be great if anyone would have any suggestions :)

p.s. My local time is 03:00 AM so i am a bit tired and overworked - so please ask me to clarify my issue again in case you have troubles guessing what i need ;)

marc wellman
  • 5,808
  • 5
  • 32
  • 59
  • 2
    H.B in post below is absolutely right. `Style.IsSealed` property is true and you can not change it an runtime. [Set Style Setter value from code-behind at runtime](http://stackoverflow.com/questions/8593580/set-style-setter-value-from-code-behind-at-runtime). [Change a window style at runtime worked on VS2008, doesn't work on VS2010](http://stackoverflow.com/questions/7428856/change-a-window-style-at-runtime-worked-on-vs2008-doesnt-work-on-vs2010) – Anatolii Gabuza Jan 08 '12 at 10:08

2 Answers2

2
var prop = ((Setter)setter).Property;
if (prop.Name.Equals("Background")
{
   //do smth
}
2

Setters in a style get sealed anyway (probably along with the containing collection once the style is in use) so you cannot modify it, styles are meant to be persistent. I would recommend you swap out the whole style with a new one or try to approach this differently.

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Setters are getting sealed ? - What an useless ideas ;) no i am just kidding :) Thank you very much for your answer - I really wasn't aware of that fact ... I will have to do a different approach without altering the style once it is initialized. – marc wellman Jan 08 '12 at 12:17