This article is part 2 of 4 in a series attempting to cover everything I think is worth knowing about styles in Silverlight 4. The previous article in the series was Styles in Silverlight: an Introduction that covered what styles are, how they can be defined and some of their limitations.
This article focuses on some more advanced topics that are handy when building more complex applications: re-using the same styles for different types, style inheritance, style precedence and style setter precedence.
Re-Using Styles for Different Types
As discussed in the previous article, all Style elements need to specify a TargetType that specifies the type of class they need to be applied to. If an application uses several different types of visual elements, this can result in having to specify different styles again and again. Let’s say for example our application has an Ellipse and a Rectangle and we want to have both of them have a blue fill. The straightforward way of doing this using Styles is declaring two different styles for each of them and applying those using StaticResources in XAML:
<usercontrol .Resources> <style TargetType="Ellipse" x:Key="CustomEllipseStyle"> <setter Property="Fill" Value="Blue"/> </style> <style TargetType="Rectangle" x:Key="CustomRectangleStyle"> <setter Property="Fill" Value="Blue"/> </style> </usercontrol> <stackpanel Orientation="Vertical"> <ellipse Width="30" Height="30" Style="{StaticResource CustomEllipseStyle}"/> <rectangle Width="30" Height="30" Style="{StaticResource CustomRectangleStyle}" Margin="0,10,0,0"/> </stackpanel>
However in this particular case it’s possible to combine these styles as Ellipse and Rectangle inherit from the same parent class: Shape. The Fill property that we are setting in the styles is defined in Shape, so we can define a single style with the TargetType set to Shape, then apply this Style to the elements:
<usercontrol .Resources> <style TargetType="Shape" x:Key="CustomShapeStyle"> <setter Property="Fill" Value="Blue"/> </style> </usercontrol> <stackpanel Orientation="Vertical"> <ellipse Width="30" Height="30" Style="{StaticResource CustomShapeStyle}"/> <rectangle Width="30" Height="30" Style="{StaticResource CustomShapeStyle}" Margin="0,10,0,0"/> </stackpanel>
So the TargetType of the style does not necessarily have to be the type of the visual element itself. It can be a parent class of the visual element if the setters within this style only refer to properties of this parent class. The XAML code for the second example is shorter, at the same time both examples look the same:
Read the rest of this entry »


