Applying Styles to Silverlight Controls

If you have several controls that you want to make look the same, instead of editing their properties individually, you can set them all at once with a style. Then if you change your mind you don’t have to edit the ‘Background’ property of 20 elements.

In your XAML just above your ‘LayoutRoot’ grid add a region for resources like this


Inside this block you can declare resources for the page such as Data Templates and Control Templates as well as styles. An style for a Grid can be declared like this:

<Style x:Key="GridStyle1" TargetType="Grid">
<Setter Property="Background" Value="#4CC8C8C8"/>
<Setter Property="VerticalAlignment" Value="Top"/>

The x:Key attribute defines a name that’s used when applying the style and the TargetType is the type of control that the style will be applied to.
Then, inside the <Style> tags, the individual properties can be set.

The style can then be applied to a Grid and all the properties set in the style will be applied to the control when your program is run.

<Grid Style="{StaticResource GridStyle1}">

The style can also be declared inside your applications App.xaml file, in the Application.Resources section. If you do that then your style can be accessed globally in your application and not just the page you declared it in.

This entry was posted in wp7Dev. Bookmark the permalink. Both comments and trackbacks are currently closed.