This is part four of eight tutorials that walk through how to build a simple 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.
<Download Code> Click here to download a completed version of the Bing Images Search sample. </Download Code>
<Download Code> Click here to download a completed version of the Digg Search sample. </Download Code>
Using Style Elements to Better Encapsulate Look and Feel
XAML supports 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 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.
Now that we've cleaned up the markup of our Page.xaml file using Style references, let's go one step further and customize the appearance of our Story data more.
To-do that let's jump to our next tutorial: Using the ListBox and Databinding to Display List Data.