In this post I am going to discuss about some basic things inside Silverlight project. When we start Silverlight the first thing we face is XAML (Extended Application Markup Language). So I am going to start form XAML which is pronounced as /ˈzæməl/.
XAML (Extended Application Markup Language)
It is a XML-based declarative language which was created by Microsoft is used to initialize structured values and objects. XAML file generally rendered by the Silverlight plug-in and displayed inside the browser window. When we compile silverlight projects, it will first converts XAML into BAML (Binary Application Markup Language) and then rendered in the web browser window.
So let’s investigate a simple Silverlight 4 Project.
To create a new Silverlight application project
1. Start Visual Studio 2010.
2. Select File > New Project
3. In the Installed Templates pane, expand the Visual C# node and select Silverlight.
![clip_image002[4] clip_image002[4]](http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/zahid/clip_5F00_image0024_5F00_thumb_5F00_265B3CA4.jpg)
Note: In the list of templates we see that there are Silverlight Application, Silverlight Business Application, Silverlight Navigation Application template. We will check all those one after another in this post.
4. In the list of templates, select Silverlight Application.
5. Specify a name and a location for the application and then click OK.
The New Silverlight Application dialog box appears as shown in the following illustration.

6. From the Silverlight Version drop-down list, select the version of Silverlight. I have chosen Silverlight 4. Click OK.
With is a few second, Visual Studio will create the Silverlight solution which will contain a Silverlight Project and one Web Application Project to host your Silverlight application.
![clip_image001[4] clip_image001[4]](http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/zahid/clip_5F00_image0014_5F00_thumb_5F00_291C1BF1.jpg)
Once done, you will see Visual Studio already created two XAML files (App.xaml & MainPage.xaml) inside the Silverlight Application project.
MainPage.xaml
MainPage.xaml is the startpage for the Silverlight application. It is possible to modify this page as per our need or we can create a new one. Let’s look at it:
- <UserControl x:Class="SilverlightApplicationDemo.MainPage"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d"
- d:DesignHeight="300" d:DesignWidth="400">
-
- <Grid x:Name="LayoutRoot" Background="White">
-
- </Grid>
- </UserControl>
App.xaml
In App.xaml file we can define application level resources (like styles, data templates and control templates).
- <Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- x:Class="SilverlightApplicationDemo.App"
- >
- <Application.Resources>
- <Style x:Key="btnStyle" TargetType="Button">
- <Setter Property="Background" Value="Yellow"/>
- </Style>
- </Application.Resources>
- </Application>
The code-behind (App.xaml.cs) is used to handle application level events such as Startup, Exit and UnhandledException. The RootVisual is used to setup the startup Silverlight UserControl. This property needs to be set in the Startup event.
- public partial class App : Application
- {
-
- public App()
- {
- this.Startup += this.Application_Startup;
- this.Exit += this.Application_Exit;
- this.UnhandledException += this.Application_UnhandledException;
-
- InitializeComponent();
- }
-
- private void Application_Startup(object sender, StartupEventArgs e)
- {
- this.RootVisual = new MainPage();
- }
-
- private void Application_Exit(object sender, EventArgs e)
- {
-
- }
-
- private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
- {
- // If the app is running outside of the debugger then report the exception using
- // the browser's exception mechanism. On IE this will display it a yellow alert
- // icon in the status bar and Firefox will display a script error.
- if (!System.Diagnostics.Debugger.IsAttached)
- {
-
- // NOTE: This will allow the application to continue running after an exception has been thrown
- // but not handled.
- // For production applications this error handling should be replaced with something that will
- // report the error to the website and stop the application.
- e.Handled = true;
- Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
- }
- }
-
- private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
- {
- try
- {
- string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
- errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");
-
- System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
- }
- catch (Exception)
- {
- }
- }
- }
Other common uses of App.xaml.cs file are:
· This application is accessible via the global static variable Application.Current. You can cast this anywhere in your application.
· Using the Install method you can prompt the user to install the application Out-of-Browser.
· The CheckAndDownloadUpdateAsync method is used when the application is running out-of-browser to ensure that the .xap file is the latest.
Silverlight Navigation Application project
![clip_image001[6] clip_image001[6]](http://msdnbangladesh.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/zahid/clip_5F00_image0016_5F00_thumb_5F00_5F897B9B.jpg)
The Silverlight Navigation Template provides a rapid means of developing page-based web applications. The two primary controls in the System.Windows.Control.Navigation namespace are Frame and Page. The Frame control hosts a single Page control utilizes the Navigation APIs to allow the user to navigate between the pages. The Page control resembles the commonly used UserControl control to hold the contents of the respected page. The project generates the default template and files for a sample page-based application. The Views Folder has pre-generated pages (AboutPage, ErrorWindow, and HomePage).
Silverlight Business Application
If we investigate Silverlight Business Application Template we will find a new addition that is the User Authentication. That is login and logout functionality. If we run the application we will find Login is displayed.
When we build Silverlight project, it will create the XAP file (SilverlightApplicationNavigationDemo.xap) and put it into the ClientBin directory of the web project. When the page loads it will pickup from the same location as the source you specified inside the aspx/html page.
XAP
A .xap (pronounced as ZAP) file is a compiled compressed output of the Silverlight application. The file is actually a .zip file that contains all the files necessary for the application such as application manifest file, compiled output assembly and other resources.
Silverlight Application (XAP) generally loads inside the ASPX or HTML pages pointing to the path to load the XAP. Web pages use the Silverlight components by loading the .xap files using the <object> tag.
Below is a list of available parameters that can be passed to the Silverlight plug-in using the <param> tag.
| Parameter | Description | Type |
| allowHtmlPopupWindow | Specifies whether the HtmlPage.PopupWindow method is allowed. Defaults to true for applications in the same domain, otherwise false. | Boolean |
| autoUpgrade | Specifies whether the plug-in should attempt to upgrade if minRuntimeVersion is newer than the current Silverlight version. Default is true. | Boolean |
| background | Plug-in background color. Default is null (white). | Color with or without alpha (RGB, ScRGB) |
| enableAutoZoom | Indicates whether the host (for certain platforms) can invoke zoom behavior that increases the DPI. Default is true. | Boolean |
| enableCacheVisualization | Indicates whether to use a non-production analysis visualization mode, which shows areas of a page that are being GPU accelerated with a colored overlay. Default is false. Do not use in production code. | Boolean |
| enableFramerateCounter | Indicates whether to display the current frame rate in the hosting browser's status bar (IE/Win only). | Boolean |
| enableGPUAcceleration | Indicates whether to use graphics processor unit (GPU) hardware acceleration for cached compositions, which potentially results in graphics optimization. (false by default) | Boolean |
| enablehtmlaccess | Specifies whether the plug-in has full access to the browser DOM. Defaults to true for applications in the same domain, otherwise false. | Boolean |
| enableNavigation | Indicates whether the hosted content in the Silverlight plug-in can use a HyperlinkButton to navigate to external URIs. Default is all. | all: the hosted content can use HyperlinkButton to navigate to any URI. none: the hosted content cannot use HyperlinkButton for navigation to an external URI. Relative URIs for internal navigation are still permitted. |
| enableRedrawRegions | Determines whether to visually indicate the areas of the plug-in that are being redrawn with each frame. This property is for performance tuning and visualization during development only; do not specify it for any deployed Silverlight-based application. Default is false. | Boolean |
| initParams | User-defined string of parameters. | Comma separated key=value pairs |
| maxframerate | Specifies the maximum number of frames per second that the plug-in can render. The default is 60. | Integer |
| minRuntimeVersion | Specifies the earliest version of the Silverlight plug-in required. | Version number |
| onError | Error handler for parse and native code run-time errors. | JavaScript function name |
| onFullScreenChanged | Function to call when the FullScreen property changes. | JavaScript function name |
| onLoad | Function to call when the plug-in has finished loading in the DOM. | JavaScript function name |
| onResize | Function to call when the plug-in size changes. | JavaScript function name |
| onSourceDownloadComplete | Function to call when the source download has completed. | JavaScript function name |
| onSourceDownloadProgressChanged | Function to call when the source download progress changes. | JavaScript function name |
| onZoom | Specifies the handler for a Zoomed event that occurs when the Silverlight plug-in content area receives a host-generated zoom event. | JavaScript function name |
| source | Specifies the address or relative path of either an initial XAML file or XAP. | URI |
| splashScreenSource | Specifies a XAML page to use as the splash screen. | URI |
| windowless | Specifies the rendering mode for the plug-in for Windows versions of Silverlight. The default is false. | Boolean |
Here is the object tag :
- <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
- <param name="source" value="ClientBin/SilverlightApplicationNavigationDemo.xap"/>
- <param name="onError" value="onSilverlightError" />
- <param name="background" value="white" />
- <param name="minRuntimeVersion" value="4.0.50401.0" />
- <param name="autoUpgrade" value="true" />
- <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50401.0" style="text-decoration:none">
- <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
- </a>
- </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
Note: the iframe element is here for cross-browser compatibility.
Summery
In the above post I have tried to integrate all the information related Silverlight Application in one place so that a beginner could get a general overview. Maybe I have missed lots of information. If anyone one would like to add anything please feel free to leave your comments. In the next post I will try to explore Silverlight Layout System.