Silverlight 2 Controls - Styles and Templates

Saturday, October 18, 2008 10:33:27 PM (GMT Daylight Time, UTC+01:00)

With the release of Silverlight 2, I’ve been working on updating a number of my existing demos as well as building a number of new ones for upcoming presentations. One of my favorite features in Silverlight 2 (And WPF) is the ability to change the visuals of a control through styles and templates, without impacting the control logic. The demo that really drove this home to me was created by Beatriz Costa. Her post on The power of Styles and Templates in WPF showed a simple yet effective way to have the visuals of controls can be altered, leaving the logic of the control intact to do all of the expected ListBox stuff. (Fire events, provide a selected item, respond to keyboard up/down). This flexibility and separation of control visuals from control logic is one of the key elements of WPF, and now Silverlight.

I started with a some basic controls on a page including a databound ListBox and a UserControl containing some TextBlocks.

image 

After applying the styles and templates the application visuals are transformed into something much more interesting, while maintaining the complete functionality of a ListBox, while appearing as a Solar System ListBox.

            <ListBox x:Name="listbox1" Height="600" Width="1000"                 
                SelectionChanged="listbox1_SelectionChanged" 
                Template="{StaticResource ListBoxTemp}"
                ItemContainerStyle="{StaticResource DefaultListBoxItemStyle}"      
                ItemTemplate="{StaticResource ListBoxItemContainerPlanet}">
            </ListBox>

image  

In order to take things a step further, I also replaced the ItemsPanel of the ListBox with a custom carousel panel. The original CarouselPanel code I started with is by Jamie Rodriguez and found here.

                <ListBox.ItemsPanel>
                    <ItemsPanelTemplate>                    
                        <local:CarouselPanel x:Name="planets" 
                            Width="800" Height="600" Grid.Row="0"  
                            Speed="0.03" UseMousePosition="False"  
                            ScalePerspective=".2" />
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>

The result is an interactive interface with the planets orbiting around the screen, while still maintaining the full functionality of the underlying ListBox below.

image

Live Demo HERE

Source Code: (Soon)

Control Customization Documentation Resources:

Styling and Templating Overview
Control Styles and Templates
Creating a Templatable Control

** And yes… I know the ongoing debate about Pluto being a “dwarf planet” and not a “real” planet any more… deal with it.

Posted in Silverlight  | Comments [5]