Creating a Customizable Media Player in Silverlight 4


Silverlight, a Microsoft product, is the application framework that provides rich interaction in thin (Web) environment. It is often weighed against Adobe's Flash. Silverlight has come a long way from the version 1.0 to the Silverlight 4.0. Refer to the section titled "References" at the end of the article that provides you the necessary links to understand the improvements in features of each version.

The User interface layout of the Silverlight application is created using XAML - markup.

The Wiki link of Microsoft clearly states the flow of a Silverlight application:

"A Silverlight application starts by invoking the Silverlight control from the Hyper Text Markup Language (HTML) page, which then loads up a XAML file. The XAML file contains a Canvas object, which acts as placeholder for other elements."

Let's see how we can develop our own customizable media player using Silverlight.

First, create a Silverlight Application. You would choose to create a Silverlight Application from the File - New Project menu. The following window would appear.

Figure 1

Figure 1

Give a name for the project, and click on OK. It would create two projects for you.

Note the sample aspx and HTML pages that are added by default. Similarly in the Silverlight Library project, the App and MainPage XAML files are added by default too.

We will modify the first project--Silverlight Library to contain the Media Player Control. The Media Player control would comprise two user controls.

The second project - the Web application would be used to pass parameters to the Silverlight application and is used to host the Silverlight Media Player Control.

The diagram below shows the composition of the Media Player control. (The final user control is called CustomizedMediaPlayer).

The Media Element is part of the default Silverlight controls. Note that there is also a Media Control available in the Silverlight Toolkit. At the end of the article, there is a link that talks about the Silverlight Toolkit.

The same link also provides you the link to download the Toolkit. It is a simple installation and ease to use.

Back to our application, modify the App.XAML.cs to hook the Startup, Exit and Unhandled Exception events. The sample code is as shown below:

public App()
//hook events
      this.Startup            += this.Application_Startup;
      this.Exit               += this.Application_Exit;
      this.UnhandledException += this.Application_UnhandledException;

Modify the Application_Startup method code like below:

private void Application_Startup(object sender, StartupEventArgs e)
   //Set Page as the Root Visual.
   this.RootVisual = new Page();

  Dictionary<string, string> inputs = new                            
  Dictionary<string, string>();

  if (e.InitParams != null)
     	   //Add the data in the initParams
    	   //to the Resource.
         foreach (var data in e.InitParams)
             inputs.Add(data.Key, data.Value);
  inputs.Add("Skin", "SimpleResources");

InitParameters: To pass information from an ASPX page to a Silverlight library, you would make use of the Property called InitParameters. They are of key-value type of collection and are comparable to vars in Flash. Yes, it would be set up in the markup of the HTML page.

One has to just pass a comma separated Key-Value pairs like shown below:


After the parameters are defined and set values, you would use the Application_Startup event handler to capture the init params. Look above for example.

The Control and the Skin parameter allow you to set the skins for the control.

Figure 3

The attached solution with this article consists of two Media player controls in the Silverlight library.

The Customized Media Player control in the Silverlight Library is the Media Control. It's comprised of ucMediaElement and ucMediaElementControl.

The ucMediaControl contains the Media Element and the ucMediaElementControl contains the controls required to navigate in the Media Control.

Let's first create the ucMediaControl: The markup would look like below:

<UserControl x:Class="SilverLightLibrary.ucMediaElement"
    xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows" >	         <Grid x:Name="LayoutRoot" Background="White" >
                <RowDefinition x:Name="VideoRow" Height="Auto" />
                <ColumnDefinition x:Name="VideoColumn" />
<Border CornerRadius="1" BorderThickness="2" Margin="2" BorderBrush="{StaticResource MyBorderBrush}">
            <MediaElement Name="mediaPlayer" Grid.Row="0"></MediaElement>

The ucMediaControl element contains a Grid. The grid has a Row and a Column. The MediaElement is present in the Row. Note the use of the Borderbrush property for the border element. It is loaded from Resources.

Creating a Customizable Media Player in Silverlight 4

The ucMediaControl contains the controls needed to navigate in the Media Player. It consists of the below components:

  • Play-Pause button
  • Video Position Slider
  • Full screen button
  • Mute button
  • Next button

Here is the markup:

<UserControl x:Class="SilverLightLibrary.ucMediaElementControls"
    Width="500" >
    <Grid x:Name="LayoutRoot" Background="Black" VerticalAlignment="Top">
<!-- Border for the media control -->
<Border CornerRadius="1" BorderThickness="2" Margin="2" BorderBrush="{StaticResource MyBorderBrush}">
<!-Stack Panel for the buttons. Set the orientation to Horizontal-->
<StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" Height="20" Background="#FF000000">
      <Button x:Name="Prev" Content="Prev" Click="PrevButton_Click" />             

<!-The Play- pause button -->
<ToggleButton x:Name="btnPlayPause" Template="{StaticResource PlayButtonTemplate}" Content="ll" Click="Button_Click"
      IsChecked="True" Margin="2,0,0,0"/>

      <!-Slider for Video Poistion -->
<Slider  MouseLeftButtonDown="sliderPosition_MouseLeftButtonDown" Margin="2,0,0,0" x:Name="sliderPosition"   ValueChanged="sliderPosition_ValueChanged"
      Width="240" Minimum="0" Maximum="1" 
MouseLeftButtonUp="sliderPosition_MouseLeftButtonUp" >

      <!-Text block to show the duration  of the video.-->
<TextBlock x:Name="txtDuration"  Height="12" Margin="2,0,0,0"
      FontFamily="Verdana" FontSize="10" Text="00:00" TextWrapping="Wrap" 
      FontStyle="Normal" HorizontalAlignment="Right"
      TextAlignment="Right" />

      <!-Button to toggle Full Screen -->
<Button x:Name="btnFullScreen" ToolTipService.ToolTip="FullScreen" Margin="2,0,0,0" Click="btnFullScreen_Click"
Template="{StaticResource ButtonTemplate}" VerticalAlignment="Center">
<Path Height="14.375" HorizontalAlignment="Stretch" 
VerticalAlignment="Bottom" RenderTransformOrigin="0.212389379739761,0.208695650100708" 
Data="M10.181361,8.375 L12.844413,11.008244 L14.125,9.7418737 L14.125,14.375 L9.675765,14.374833 L10.906104,13.158273 L8.125,10.408315 L10.181361,8.375 z M3.9666855,8.375 L6,10.431361 L3.3667567,13.094413 L4.6331258,14.375 L0,14.375 L0.00016707927,9.925765 L1.2167276,11.156104 L3.9666855,8.375 z M9.4918737,0 L14.125,0 L14.124833,4.449235 L12.908273,3.2188957 L10.158315,6 L8.125,3.943639 L10.758244,1.2805867 L9.4918737,0 z M0,0 L4.449235,0.00016686507 L3.2188957,1.2167276 L6,3.9666855 L3.943639,6 L1.280587,3.3667567 L0,4.6331258 L0,0 z"
Fill="#FF7F7F7F" Stretch="Fill" Stroke="#FF000000" StrokeThickness="0" />

	<!-Text Block for Volume. -->
<TextBlock x:Name="txtVol" Text="Vol:" VerticalAlignment="Center" Margin="2,0,0,0"></TextBlock>
      <Slider x:Name="sliderVolume" Margin="2,0,0,0"  
      Style="{StaticResource SliderStyle}" Width="50"      
VerticalAlignment="Center" ValueChanged="sliderVolume_ValueChanged" Minimum="0" Maximum="1"  ></Slider>

      <!-The Mute button -->
      <ToggleButton IsChecked="false"  x:Name="btnMute" 
Template="{StaticResource MuteButtonTemplate}" Click="btnMute_Click" VerticalAlignment="Center" Margin="2,0,0,0" Content="On"/>

      <!-The Next button -->
      <Button x:Name="Next" Content="Next" Click="NextButton_Click" >


Now, let's create the Media Player user control that would consist these two user controls.

<UserControl x:Class="SilverLightLibrary.CustomizedMediaPlayer" x:Name="ucSkin1Player"
    	xmlns:ns="clr-namespace:SilverLightLibrary" Height="700"
        <Grid x:Name="LayoutMedia" Background="White" >
                <RowDefinition  Height="Auto"></RowDefinition>
                <RowDefinition  Height="Auto" ></RowDefinition>
<ns:ucMediaElement x:Name="ucMediaPlayer" Grid.Row="0"></ns:ucMediaElement>
<ns:ucMediaElementControls x:Name="ucMediaPlayerControls" Grid.Row="1" VerticalContentAlignment="Top" VerticalAlignment="Top"></ns:ucMediaElementControls>

The media player and the controls are added to the New User Control. Go to code-behind and set the mediaplayer Element property of the ucMediaPlayerControl to associate the mediaplayer.

public CustomizedMediaPlayer()
ucMediaPlayerControls.MediaPlayerElement = ucMediaPlayer;

Go to the Page.XAML file now. Add the code to read the initParams from the Resources and create an instance of the CustomizedMediaPlayer control.

Private void Page_Loaded(object sender, RoutedEventArgs e)
Dictionary<string, string> inputParams = new Dictionary<string, string>();
      if (App.Current.Resources["InputParams"] != null)
inputParams = App.Current.Resources["InputParams"] as Dictionary<string, string>;

      string currentSkin      = string.Empty;
if (inputParams.ContainsKey("Skin"))
      	currentSkin = inputParams["Skin"].ToString();
Uri resourceUri = new Uri(string.Format("/SilverLightLibrary;component/Themes/{0}.xaml", currentSkin), UriKind.RelativeOrAbsolute);
            ResourceDictionary simpleStyles = new ResourceDictionary();
            simpleStyles.Source = resourceUri;

double height = width = 600;

if (inputParams.ContainsKey("Height"))
          height = Double.Parse(inputParams["Height"].ToString());
      if (inputParams.ContainsKey("width"))
          width = Double.Parse(inputParams["width"].ToString());

//Create the customized media player.
 CustomizedMediaPlayer mediaPlayer = new CustomizedMediaPlayer();
      mediaPlayer.Name = "mediaPlayer";
mediaPlayer.Height = height;
mediaPlayer.Width = width;

Figure 4

Note that the themes are loaded from the Predefined Themes folder. And also the height and width of the customized media player are set from the Initparams.

When you compile the


Library project (the one that has the user controls, it would create a XAP file and get copied to the ClientBin folder of the Sample Web application.

The filename would be SilvelightLibrary.xap.

Now, the missing part is the configuration that has to be provided in the InitParams collection in the html file.

Open the "SilverLightSampleTestPage html" file in the Sample project and add the following to the body tag.

  <div id="silverlightControlHost" style='Height:500px; Width:500px'>
<object data="data:application/x-silverlight-2," type="application/x-  silverlight-2" width="100%" height="100%">
	<param name="source" value="ClientBin/SilverLightLibary.xap"/>
	<param name="onerror" value="onSilverlightError" />
	<param name="background" value="white" />
	<param name="minRuntimeVersion" value="2.0.31005.0" />
	<param name="autoUpgrade" value="true" />
<param name="initParams" 
MediaSource=" />
<a href="" style="text-decoration: none;">
<img src="" alt="Get Microsoft Silverlight" style="border-style: none"/>
	<iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>

Note the InitParams tag.

The screenshots below of the sample application shows the video being played with the default settings.

Figure 5

The entire sample is provided with the article to download.

Silverlight Tooklit from CodePlex

The Silverlight toolkit from CodePlex too has a Media Player control for us to use. It comes with about 10 themes to select from. If you are running out of time, or want to just plug-and-play the mediaplayer into your application , I would suggest you to use the Toolikit.

The link is provided in the References section.


Related Articles

About the Author

Srinath M S

I would love to leave a footprint in this flat world



  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • Recently, Forrester Consulting conducted a Total Economic Impact™ (TEI) study to better understand the impact of incorporating Polycom voice solutions with Microsoft Lync. Forrester interviewed a company that had already deployed the Lync/Polycom combination to determine its potential return on investment (ROI). Microsoft Lync provides presence information and promotes voice and video collaboration. Polycom extends the benefits of Lync with voice endpoints and further enables collaboration in multiple …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds