Styling Windows Phone Silverlight Applications
- by Tim Murphy
If you have not developed with styles in Silverlight/XAML then it can be challenging and resources can be sparse depending on how deep you get. One thing that you need to understand is what level you can apply styles and how much they can cascade. What I am finding is that this doesn’t go to the level that we are used to in HTML and CSS. While styles can be defined at a page level if you want to share styles throughout your application they should be defined in the App.xaml file. This is of course analogous to placing a style in your HTML file versus an external CSS file. This is the type of style I will concentrate on in this post. The first thing to look it how styles associate to elements. TargetType defines the object type that your style will apply to. In the example below the style is targeting the TextBlock object type. <Style x:Key="TextBlockSmallGray" TargetType="TextBlock">
Next we use a Setter which allows you to apply values for specific attributes of the target object type. The setters can be a simple value or complex. The first example here is simply applying a color to the background property of the target.
<Setter Property="Background" Value="White"/>
The second setter example here is for the same property, but we are applying a the definition of a LinearGradientBrush.
<Setter Property="Background"> <Setter.Value> <LinearGradientBrush> <GradientStop Offset="0" Color="Black"/> <GradientStop Offset="1" Color="White"/> </LinearGradientBrush> </Setter.Value> </Setter>
The last thing I want to cover here is that you can leverage the system styles and then override or extend them. The BasedOn attribute of the Style tag allows this sort of inheritance. In the example below I am going to start with the PhoneTextTitleStyle and then override properties as needed.
<Style x:Key="TextBlockTitle" BasedOn="{StaticResource PhoneTextTitle1Style}" TargetType="TextBlock">
So now that we have our styles defined applying it is fairly straight forward. Add the style name as a static resource to the style property of the element in your page and off you go.
<Grid x:Name="LayoutRoot" Style="{StaticResource PageGridStyle}">
So this is one step in creating consistency in your application’s look. In future posts I will dig a little deeper.
del.icio.us Tags: windows phone 7,mobile development,windows phone 7 development,.NET,software development,design,UX