Set the Style of a control programatically in Silverlight 4?
I am new to Silverlight, but I couldn't find anything about this when I googled it.
I have a button that 开发者_运维知识库I am trying to set the style programatically. I have the style defined in a XAML file and I want to pull the style into C# so I can dynamically create a button and assign it this style. So far, this is what I am trying:
button.Style = (Style)Resources["CloseButtonStyle"];
However, it just makes the button have no style. Is there an easy way to do this? I feel like this should be obvious, but I can't get it to work.
You are assuming that your Resources
property on the current object is the one that contains the defined style. However, I assume, given the symptoms of your issue, that CloseButtonStyle
is actually defined further up the control hierarchy.
Instead, you need to traverse your control hierarchy until you find the resource (or if you know the object that defines it, just refer directly to that object). Unfortunately, Silverlight doesn't include FindResource
call like WPF, but it's not too difficult to implement your own.
I can call button1.Style = (Style)Resources["NonExistentKey"];
and it makes my button have no style at all as well, point being that the resource is probably not being found, you won't get an exception.
You directly access the Resources
property, but is the style really in the immediate resource dictionary of your Window/UserControl/whatever-you-have?
精彩评论