Click here to Skip to main content
15,880,405 members
Articles / Programming Languages / C# 4.0

Metro Style ListBox in Silverlight

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
29 Apr 2013CPOL4 min read 23K   1.1K   5  
create Metro theme listbox using style and templates

 


Introduction 

Metro theme designed by Microsoft for use of Windows Phone 7.  A key design principle of Metro is better focus on the content of applications, relying more on typography and less on graphics. 

For the Metro style, proprietary principles have been developed, used by Microsoft to create its own operating system and applications. Windows 8 OS created in metro interface.

Afterwords many web applications built using Metro- theme.  

Background 

ListBox is very useful control in silverlight. user can change appearance of listbox control using its style and templates.

Using ControlTemplate user can customize appearance of the listbox control.

Using DataTemplate, we can customize how data is display.

In this post we will go through modifying ListBox ControlTemplate to looks like metro style (see below image ). 

 

Image 1




Using the code

Step 1 : 

First, Create ResourceDictionary file, that contains Resources, styles and Templates for the applications.

Styles.xaml 

C++
 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:control="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit">
</ResourceDictionary>   

As shown in above code, i have added prefix xmlns:control for mapping namespace of System.windows.control.

To arrange items in horizontally or vertically (wrap items in listbox)  WrapPanel is used.

WrapPanel control is available in silverlight toolkit, you can download Silverlight Toolkit from codeplex.

if you are using silverlight 4 then click Link  to download  Silverlight 4 Toolkit - April 2010.

if your application is developed in silverlight 5 then click Link to download Silverlight 5 Toolkit - December 2011. 

Donwload toolkit .msi and Install it, new ddls are added in following path :

C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Libraries\Client 

Image 2

Step 2 : Now add  System.Windows.Controls.Toolkit.dll reference in the application. 

This dll contains following addition controls :    

Image 3

Step 3 : Now, Create ListBox Style. 

<Style x:Key="MetroListBox" TargetType="ListBox">
   <Setter Property="BorderBrush" Value="Transparent" />
   <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
   <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
   <Setter Property="HorizontalAlignment" Value="Stretch" />
   <Setter Property="HorizontalContentAlignment" Value="Stretch" />
   <Setter Property="ItemsPanel">
       <Setter.Value>
           <ItemsPanelTemplate>
               <control:WrapPanel Orientation="Horizontal" />
           </ItemsPanelTemplate>
           </Setter.Value>
       </Setter>
       <Setter Property="ItemTemplate">
           <Setter.Value>
               <DataTemplate>
                   .......
                   <!-- Your Data -->
                   .......
               </DataTemplate>
           </Setter.Value>
       </Setter>
   </Style>

To create a style for a control, you have to set TargetType property, TargetType property used to set style for the control of given TargetType FrameworkElement. 

 Based on targetType style automatically provides list of available setter property for given controls. and Key is used for applying specific style to the control. 

ItemsPanel property sets the template that defines the panel that controls the layout of items. 

ItemsPanelTemplate that defines the panel to use for the layout of the items. The default value for the ItemsControl is an ItemsPanelTemplate that specifies a StackPanel. others are ( WrapPanel, VirtualizingStackPanel etc.)  

I have added WrapPanel within ItemsPanelTemplate , and sets the Orientation property to Horizontal, it will wrap Items within ListBox if the items total width will exceeds the width of ListBox.  

ItemTemplate property is used to specify visual appearance of you data. You can use a DataTemplate to define the appearance of your data objects. using DataTemplate you can change the display structure of data. like : 

 Image 4

Image 5

 If you do not set the ItemTemplate,  the ItemsControl displays the string representation of the objects in a collection. 

Step 4 :

Now, create ListBoxItem style. 

C++

C++
 <Style x:Key="MetroListBoxItem"   TargetType="ListBoxItem">
	<Setter Property="Height" Value="70" />
	<Setter Property="Width" Value="180" />
	<Setter Property="Margin" Value="1" />
	<Setter Property="Template">
	   <Setter.Value>
	       <ControlTemplate TargetType="ListBoxItem">
		   <Grid>						
			<Border x:Name="fillBorder"
			   Background="{StaticResource ListItemBackgroundBrush}"
			   BorderThickness="0">
				<ContentPresenter x:Name="contentPresenter"
				   Margin="{TemplateBinding Padding}"
				   HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
				  Content="{TemplateBinding Content}"
				  ContentTemplate="{TemplateBinding ContentTemplate}" />
			</Border>
			<Rectangle x:Name="FocusVisualElement"
				RadiusX="1"
				RadiusY="1"
				Stroke="#116690"
				StrokeThickness="3"
				Visibility="Collapsed" />
		    </Grid>
		</ControlTemplate>
	    </Setter.Value>
	</Setter>
</Style> 
C++

Created Style with TargetType=ListBoxItem, will apply style to the items within ListBox. 

The ControlTemplate speicifies the visual looks and appearance of the control.

using CotrolTemplate you can customize visual appearance of existing control like ( Adding Animation, Scale/Translate/Rotate control, add Circle around the control etc.)

As shown in above code, I have placed ContentPresenter within Border and  Border is placed  within ControlTemplate.  

 It will display item with Border around it. 

By setting Background Color of the border, each items will highlighted with given color.  

Added Rectangle control with its Stroke Color and StrokeThickness=3 and Visibility=Collapsed.

This Rectangle control is visible when user select any item ( Focused ).. 

Step 5 : 

Next, add VisualStates to the ListBoxItem for apply mousehover style and selected item style.

 

C++
<VisualStateManager.VisualStateGroups>
   <VisualStateGroup x:Name="CommonStates">
	<VisualState x:Name="Normal" />
	<VisualState x:Name="MouseOver">
	   <Storyboard>
		<DoubleAnimation Duration="0" Storyboard.TargetName="fillBorder"
			Storyboard.TargetProperty="Opacity" To=".8" />
	   </Storyboard>
	</VisualState>
   </VisualStateGroup>
   <VisualStateGroup x:Name="SelectionStates">
	<VisualState x:Name="Unselected" />
	<VisualState x:Name="Selected">
	   <Storyboard>
		<ColorAnimationUsingKeyFrames Storyboard.TargetName="fillBorder" 
                    Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)">
			<SplineColorKeyFrame KeyTime="0:0:0.5" Value="#CC0080AA" />
		</ColorAnimationUsingKeyFrames>
	   </Storyboard>
	</VisualState>
   </VisualStateGroup>
   <VisualStateGroup x:Name="FocusStates">
	<VisualState x:Name="Focused">
	   <Storyboard>
		<ObjectAnimationUsingKeyFrames Duration="0"
			Storyboard.TargetName="FocusVisualElement"
			Storyboard.TargetProperty="Visibility">
			      <DiscreteObjectKeyFrame KeyTime="0">
				  <DiscreteObjectKeyFrame.Value>
					<Visibility>Visible</Visibility>
				  </DiscreteObjectKeyFrame.Value>
			      </DiscreteObjectKeyFrame>
		</ObjectAnimationUsingKeyFrames>
	   </Storyboard>
	</VisualState>
   <span class="Apple-tab-span" style="white-space: pre;">	</span><VisualState x:Name="Unfocused" />
   </VisualStateGroup>
</VisualStateManager.VisualStateGroups> 
C++

VisualStateManger play vary important role for animation in silverlight. 

let's first go through small introduction to Animation. 

Animation

Animation is used to creating rich user interface, like :

 - change the opacity of control

 - resize control ( change size from small to large and large to small)

 -  moving control from one location to another 

Storyboard is a container timeline that provides object and property targeting information for its child animations.
The Storyboard class provides the Storyboard.TargetName and

Storyboard.TargetProperty attached properties. You set these properties

on an animation to specify its target object and property. 

following are types of animations available : 

 1. DoubleAnimation

 2. ColorAnimation

 3. ObjectAnimationUsingKeyFrames / DoubleAnimationUsingKeyFrames / ColorAnimationUsingKeyFrames

  

VisualStateManger used to manages states and the logic for transitioning between states for controls. 

VisualStateGroup is collections of VisulState objects like (Foucsed, Selected, Normal, MouseOver etc.)

VisualState Represents the visual appearance of the control when it is in a specific state. 

I have added DoubleAnimation in this example for change the opacity of the ListItem when user moves mouse over on it. 

On ColorAnimation is applied on Selected VisualState , it will change the backgroud color of the border ( ListItem ) when user select the Item.

Same way on Focus, Rectangle will appear (visible) and thick border appear around the Focused Item.

 So, this way you can create animation for the control. 

Step 6 :

Now Add ResourceDictionary (Style.xaml) to App.xaml page.

 

C++
 <Application x:Class="MetroStyleListBox.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
   <Application.Resources>
     <ResourceDictionary>
	 <ResourceDictionary.MergedDictionaries>				
	     <ResourceDictionary Source="/MetroStyleListBox;component/Resources/Styles.xaml" />
	 </ResourceDictionary.MergedDictionaries>
     </ResourceDictionary>
   </Application.Resources>
</Application> 
C++

  Step 7 :

Create UserControl, place ListBox wihtin it and apply Style & ItemContinerStyle. 

 

C++
<Grid x:Name="LayoutRoot" Background="Transparent">
		<ListBox x:Name="lbActiveCall"
		         Grid.Row="1"
		         Grid.ColumnSpan="2"
		         Width="600"
		         Height="300"
		         ItemContainerStyle="{StaticResource MetroListBoxItem}"
		         ItemsSource="{Binding FlowerCollection}"
		         Style="{StaticResource MetroListBox}" />
</Grid>
C++

In above source, added StaticResources for ListBox Style and ListBoxItem Style (ItemContainerStyle), it will apply styles to the control.

This way, you can customize ControlTemplate of the control to change the appearance of the control. 

 I have also created Scrollviewer style and it available in attached zip. 

C++
 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader Reputed IT Company
India India
Having 9+ years of experience in Microsoft.Net Technology.
Experience in developing applications on Microsoft .NET Platform ( Asp.Net, WPF, Silverlight, Windows Phone 7/8).
Experience and knowledge of software design methodologies (Agile), object oriented design, and software design patterns (MVVM).
Experience in Developing android mobile application using Xamarin (mono for android) framework.

http://hirenkhirsaria.blogspot.com/

Comments and Discussions

 
-- There are no messages in this forum --