Silverlight 4.0 Implicit Styles: Not so implicit after all!

Silverlight 4.0 allows you to define implicit styles that are applied automatically to all controls of the type specified in the Style TargetType property, you can create an implicit style by creating a Style without any key, for example here is an implicit style for the TextBlock control

  1. <Style TargetType="TextBlock">
  2.                         <Setter Property="FontFamily" Value="Freestyle Script" />
  3.                         <Setter Property="FontSize" Value="30" />
  4.                     </Style>

This style will be applied to all the TextBlocks that don’t define an explicit style, excellent.. right?, unfortunately this will not work for the controls defined inside a Template, for example if you have a  DataTemplate that contains a TextBlock, the TextBlock will not pick the implicit style, Microsoft explains the behaviour

“Templates are viewed as an encapsulation boundary when looking up an implicit style for an element which is not a subtype of Control.”

This explains why this doesn’t work for the TextBlocks (not a subtype of Control), the same settings will work for the Button control because it is a subtype of Control.

The solution is to use explicit styles or move the implicit style to be inside the template.

For more details please refer to the following links

http://www.11011.net/archives/000692.html

http://www.sharpfellows.com/post/Automated-Tool-Tip-for-TextBlocks-in-DataTemplates.aspx

Comments

Anonymous said…
Another workaround is to create a usercontrol as your template, and reference the usercontrol in the template.

<DataTemplate>
   <local:MyItemTemplate/>
</DataTemplate>
Anonymous said…
Thank you both poster and commenter! I've been looking for my custom controls weren't working with implicit styles. Now I know why it isn't working and how to fix it. Thank Jeebus for you guys.

Popular posts from this blog

Documentum DQL Query Custom Data Extension For SQL Server Reporting Services

Portable Class Library Projects and MVVM Light

Using taco to create Ionic projects for the Windows platform