Using Style Elements to Better Encapsulate Look and Feel
This is part four of eight tutorials that walk through how to build a simple Digg client application using Silverlight 2. These tutorials are intended to be read in-order, and help explain some of the core programming concepts of Silverlight. Bookmark my Silverlight 2 Reference page for more of Silverlight posts and content.
<Download Code> Click here to download a completed version of this Digg client sample. </Download Code>
Using Style Elements to Better Encapsulate Look and Feel
WPF and Silverlight support a Style mechanism that allows us to encapsulate control property values as a reusable resource. We can store these style declarations in separate files from our pages, and re-use them across multiple controls and pages in an application (as well as re-use them across multiple applications). This is conceptually similar to using CSS with HTML when doing basic customization scenarios.
Note: In addition to defining basic property settings (Color, Font, Size, Margins, etc), styles in WPF and Silverlight can also be used to define and re-use Control Templates - which enable super rich skinning and adaptation of control structure (and support customization scenarios not possible with CSS in HTML today). I discuss Control Templates in Part 7 of this series.
For our Digg sample application we'll define our Style declarations within the App.xaml file of our project. This will enable them to be reused across all pages and controls in the application:
Let's start by encapsulating styles for the <Border> control (and the <TextBlock> title contained within it) of our Digg page:
We can create two Style elements within our App.xaml file that encapsulate the <Border> and <TextBlock> settings we were previously declaring inline using the markup below:
Note how we are giving each Style a unique "Key" value above. We can then update our <Border> and <TextBlock> controls to reference the Styles using these keys. We'll be using a XAML feature called "markup extensions" to do this. Markup extensions are used when there are non-literal values that we want to set (another example of where we'll use this feature is with databinding expressions).
When we update the other controls within our Page.xaml file to use styles as well, we are left with a file that looks like below:
Encapsulating the style settings this way allows developers to better focus on the behavior semantics of the application, and also enables us to re-use styles across other controls/pages we build.

浙公网安备 33010602011771号