Thursday, July 18, 2013

SilverLight Light

What is silverlight ?


This gives an introduction to the new Microsoft Silverlight technology.
Silverlight is a web based technology, launched by Microsoft in April 2007. Silverlight is considered as a competitor to Adobes Flash.

Silverlight applications are delivered to browsers in a text-based markup language called XAML. One important difference between Flash and XAML is, Flash is a compiled application where as XAML is text based. Search engines can analyze and index such content, which is a huge benefit for webmasters.

For regular internet users, Silverlight is a browser plug-in that supports video, audio and animations.

For web developers, Silverlight offers much more. Silverlight supports video and audio files without need of much programming. It allows them to handle events from web pages (like handle start/end of video playing etc)

Difference between Silverlight 1 and Silverlight 2


This chapter explains some of the primary differences between Silverlight 1 and Silverlight 2
Silverlight 1 is purely AJAX and Javascript based. All the code has to be written in Javascript and XAML.

Silverlight 2 supports managed code. When Silverlight 2 runtime is installed, it installs a limited version of .NET runtime on the client machine. This allows .NET programmers to write managed code to be executed on the client PC and provide a better user experience to the users. Of course, there is security and restrictions built in to it so that the code has limited access to the client computer.

Developers must be aware that if the end user decline to install the .NET runtime on their client computer, the Silverlight 2 applications will not run.

Difference between Silverlight and WPF


This chapter explains some core differences between Silverlight and WPF (Windows Presentation Foundation)
Silverlight and Windows Presentation Foundation (WPF) are 2 different products from Microsoft, but has lot of overlap. Silverlight is a sub set of WPF in terms of features and functionality.

Silverlight is a Microsoft technology, competing with Adobes Flash and is meant for developing rich browser based internet applications.

WPF is a Microsoft technology meant for developing enhanced graphics applications for desktop platform. In addition, WPF applications can be hosted on web browsers which offers rich graphics features for web applications. Web Browser Appliactions (WBA) developed on WPF technology uses XAML to host user interface for browser applications. XAML stands for eXtended Application Markup Language which is a new declarative programming model from Microsoft. XAML files are hosted as descrete files in the Web server, but are downloaded to the browsers and converted to user interface by the .NET runtime in the client browsers.

WPF runs on .NET runtime and developers can take advantage of the rich .NET Framework and WPF libraries to build really cool windows applications. WPF supports 3-D graphics, complex animations, hardware acceleration etc.

Tools required to develop Silverlight applications


This chapter talks about various development tools available to develop Silverlight applications.
To run Silverlight applcations in a web browser, you need to have Silverlight run time installed on the client browser as a plug in. This is a light weight version of .NET runtime.

However, to develop a Silverlight application, you need something more.

Silverlight SDK

This include a set of tools required to compile and build Silverlight controls.

If you are comfortable writing HTML using notepad and compiling .NET applications from console tools, then you just need the Silverlight SDK to develop Silverlight applications.

However, most people use some kind of IDE to develop applications faster.

Microsoft offers 2 separate tools to develop Silverlight applications:

1. Microsoft Expression Studio - this tool is meant for web designers to create rich visual elements for Silverlight applications. Expression Studio is recommended for web designers who create rich internet applications with enhanced visual content and graphics. There are several features provided for creating enhanced graphics elements with lot of options to pick color, font etc.

2. Microsoft Visual Studio - this is the integrated development environment from Microsoft to develop .NET applications. Programmers can use Visual Studio to develop Silverlight applications which require programming. Visual Studio allows programmers to develop sophisticated Silverlight applications in any .NET language (like C#, VB.NET etc).

If you are using Visual Studio, you can download the Silverlight development tools from here. This download include the Service pack1 for VS.NET and the Silverlight SDK.

Which tool to use - Expression Studio or Visual Studio ?

If your Silverlight application include just graphics adn visual elements, then you can use Expression Studio. However, if you are a programmer and if your Silverlight application include programming logic, then you might want to choose Visual Studio.

Difference between Silverlight Runtime and Silverlight SDK


In this tutorial, you can learn more about the difference between Silverlight Runtime and Silverlight SDK
Silverlight Runtime is a plug-in for browsers to support Silverlight enabled applications. If Silverlight runtime is not installed, browsers will not be able to run Silverlight elements in the browser. You can set up your Silverlight tags such a way that your browser will automatically prompt the user to download and install the Silverlight plug in when your application is launched in the browser.

Installing the run time is a one time operation on the client. Once installed, it will be automatically launched when any Silverlight application is loaded in the browser.

Silverlight SDK is a set of tools, documentation, samples and templates for the web developers to help them easily develop Silverlight enabled applications. The SDK is not really mandatory to develop Silverlight applications, however, SDK will make development much easier.

What is XAML ?


This chapter gives an introduction to XAML - the eXtended Application Markup Language
XAML stands for eXtended Application Markup Language. XAML contain XML that is used to declaratively specify the user interface for Silverlight or WPF applications.

For example, if you need to display a rectangle, this is the XAML you need to use:


    <Canvas Width="500" Height="500" Background="White">
        <Rectangle Canvas.Left="75" Canvas.Top="90" Fill="red" Width="100" Height="100" />
    </Canvas>


When the above xaml is executed, it will display a rectangle filled with red color.

You may notice is that XAML is very similar to HTML in nature.

What is .xap file ?


This chapter explains the purpose of .xap file in Silverlight applications
.xap file is the compressed output file for the Silverlight application. The .xap file includes AppManifest.xaml, compiled output assembly of the Silverlight project (.dll) and any other resource files referred by the Silverlight application.

Web pages like .aspx files and .html files use the Silverlight components by loading the .xap files using the <object> tag in the HTML or by using <asp:Silverlight> tag in the ASP.NET pages.

".xap" files (pronounced "zap") use the standard .zip compression algorithm to minimize client download size. A "hello world" .NET Silverlight application (built using VB or C#) is about 5KB in size.

Let us see how a .xap file look like.

Open Visual Studio and create a new project by selecting "Silverlight Application" under the project type "Silverlight". Choose the project name "SilverlightTest". In the next screen, choose the option "automatically generate a test page to host Silverlight at build time".

Visual Studio creates a project with 2 files:

1. App.xaml
2. Page.xaml

Compile and run the application by pressing Ctrl + F5. You can see the browser opening with an empty page (the page is empty because you have nothing in your default xaml file).

Now open your windows explorer and look in to the bin\debug folder of your project. You can see a file called "SilverlightTest.xap".

Rename this file to SilverlightTest.zip and open it using any decompression tool. You can see that this is just like any other zip file and it includes the projects output dll and another file called "AppManifest.xaml".

"Hello World" Silverlight application


In this chapter, you will learn how to create your first Silverlight application
Open Visual Studio and select the menu "File" > "New" > "Project"
Select the Project Type as "Silverlight" under your favorite language and choose the template "Silverlight Application". I have selected Visual C# as the tutorials here.

I have named my project as "MySilverlightApp" and have selected the option "Create directory for solution" so that all my project files are organized within a folder structure.



We need a web page to host the Silverlight components that we develop. Visual Studio makes this job easier in the next step by prompting you to automatically create a website. Choose the options as shown in the attachment.



You are ready to rock ! Just press OK and Visual Studio will create 2 projects and a bunch of files for you. We will analyze some of the files created by Visual Studio in the next chapter.

Files created by Visual Studio by default


In this chapter, let us analyze some of the files created by default by Visual studio
 When we create a new Silverlight application using Visual Studio 2008, it creates several files by default. See the solution explorer immediately after creating a new Silverlight project with a host website:



We will analyse some of the files.

AppManifest.xml

This file defines the assemblies that are deployed to the client applications.

Build and run your Silverlight hello World application


In this chapter, you will learn how to build and run your Silverlight application
It is time to build and run your first Silverlight application. Press Ctrl+F5 to build and run your application. If everything is setup correctly, then Internet Explorer will be launched automatically with your default page which hosts your Silverlight object.

Since you have not done much for your control, you will see a blank page opened in the browser.

Go back to your Visual Studio and open your web page which hosts the Silverlight object. In my sample project, the file is named "MySilverlightAppTestPage.aspx" and the content of the file looks like this:


 
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Register Assembly="System.Web.Silverlight" 
  Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;">
<head runat="server">
<title>Test Page For MySilverlightApp</title>
</head>
<body style="height:100%;margin:0;">
<form id="form1" runat="server" style="height:100%;">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div style="height:100%;">
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/MySilverlightApp.xap" 
  MinimumVersion="2.0.30523" Width="100%" Height="100%" />
</div>
</form>
</body>
</html>


Most of the stuff above look familiar to ASP.NET developers. Some of the lines that need some attention are:

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/MySilverlightApp.xap" 
 MinimumVersion="2.0.30523" Width="100%" Height="100%" />


The second line defines the Silverlight control to be hosted in the web page. The attribute "Source" defines the .xap file to be used by the web page. This .xap file contains the XAML and code from your .xaml files and will be executed by the Silverlight plugin.

In the current sample, you have just one xaml file called Page.xaml. When you compile the solution, this file is compiled into a special file (MySilverlightApp.xap) with the extension .xap.

What is app.xaml ?


This chapter explains the significance of app.xaml file in a Silverlight application.
App.xaml is a file used by Silverlight applications to declare shared resources like brushes, various style objects etc. Also, the code behind file of app.xaml is used to handle global application level events like Application_Startup, Application_Exit and Application_UnhandledException. (Similar to Global.asax file for ASP.NET applications)

When Visual Studio creates the app.xaml file automatically, it creates few event handlers with some default code. You can change the code appropriately.

 
private void Application_Startup(object sender, StartupEventArgs e)
{
}

private void Application_Exit(object sender, EventArgs e)
{
}

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
} 

For ASP.NET developers, the above code will look familiar. This is similar to the aplication level event handlers in Global.asax.

Page.xaml file


This chapter gives an introduction to the Page.xaml file automatically created by Visual Studio while creating a Silverlight project.
When you create a Silverlight project using Visual Studio 2008, it creates a default xaml file called "Page.xaml". This is just a dummy start page created by Visual Studio and it does not contain any visible UI elements. The default content of the page.xaml file looks like this:

 
<UserControl x:Class="MySilverlightApp.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Width="400" Height="300">
  <Grid x:Name="LayoutRoot" Background="White">

 
  </Grid>
</UserControl>


The above code shows a user control and a Grid control. The UserControl is a high level control that holds all other UI elements in a xaml file.

The Grid control is used as a layout panel and it can hold other UI elements. All UI elements in a .xaml control must be placed within a layout panel. There 3 different types of layout panels available in Silverlight 2.0. You will learn more about layout controls in a later chapter.

When you compile your Silverlight Application project, it will compile all .xaml files and various other resources in to a single assembly file. This assembly file will have the extension .xap and will have the same file name as your project name.

To place your Silverlight control in a web page, you must refer to this .xap file in your web page. When the .xap file is referred in a web page, the default .xaml page will be shown. Based on user actions, you may open or close various .xaml files included in your .xap assembly (Silverlight Application project). 

Getting started with XAML tags


This chapter gives an introduction to the XAML tags in Silverlight applications.
Let us add a xaml tag to your Page.xaml file and see how it works.

Open page.xaml file from your Visual Studio project and place the following code within the Grid element:

<Rectangle Fill="Blue" Width="100" Height="100"/>

Now compile and run the application. You can see a blue rectangle displayed in your web page.

As demonstrated above, the elements in a Silverlight xaml page are declared using XAML tags. Silverlight 2 offers several XAML tags including common form tags like textbox, button etc and various other UI elements like rectangle.

One nice thing about Visual studio is, it will show you a preview of the page as you type the xaml tags. When you complete typing the above xaml tags in your .xaml page, you will see the design preview in Visual Studio as shown below:



You can swap the position of the code and preview by pressing the icon with 2 arrows in the middle of the screen (between the tabs "XAML" and "Design". Also, you can use the icons on the right end between the code and design panes to change the position of the code pane and design preview.

How to place a Silverlight control in a web page ?


This chapter explains how to place silverlight controls in a web page.
Each Silverlight Application project can have multiple .xaml pages. When you create a new Silverlight Application project, Visual Studio creates a default .xaml file called Page1.xaml. To add more .xaml pages, right click on the project in the Solution Explorer and select "Add" and "New Item". Then select "Silverlight User Control"

One or more Silverlight Applications can be placed in a web page using xaml tags as shown below:

 
<asp:Silverlight ID="Xaml1" runat="server" 
         Source="~/ClientBin/MySilverlightApp.xap" 
         Width="300" Height="300" />
 

In the above tag, the attribute "source" represents the name of the xap file which is the compiled output of the Silverlight project. The .xap files contains the compiled version of all .xaml files included in the Silverlight Application project.

When you compile the Silverlight Application project, it will be compiled to an assembly with the extension .xap. For example, if your Silverlight project name is "MySilverlightControl", when compiled, it will produce the assembly MySilverlightControl.xap

Each Silverlight project can have multiple .xaml files. Each .xaml file is like a page or form by itself. When you place a Silverlight Application in a web page, only one .xaml control will be visible at a time. Based on various user actions, you may dynamically open various .xaml pages (Just like you open forms in a windows application).

How to set default .xaml page in a Silverlight control ?


This chapter demonstrates how to change the default .xaml page used in a Silverlight control
Each Silverlight project can have multiple .xaml files. However, only one .xaml file will be visible at a time.

When you create a Silverlight project in Visual Studio, it will create a .xaml file called "Page1.xaml" by default and this .xaml control will be displayed by default when you open the web page.

You can change the default .xaml page by setting the property "Application.RootVisual".

To try this, add a .xaml file called "Page2.xaml" in your silverlight project.

Now, open your App.xaml.cs file in the Silverlight project. Look at the Application_Startup event handler. There you can see the default .xaml page being set. To change the default .xaml page, you have to specify the name of the class used in the .xaml page and set it to the Application.RootVisual property as shown below:


private void Application_Startup(object sender, StartupEventArgs e)
{
     this.RootVisual = new Page2();
}

After you change the value here, compile the application and run. When the web page is opened, you can see that the new .xaml control is displayed in the web page.

How to open XAML pages from another XAML page ?


This chapter shows how to open a xaml page from another xaml page.
In a Silverlight application, you can have multiple XAML pages. When you use the .xap file in the web page, only one XAML control will be displayed at a time. The default XAML file displayed is determined by the following code in the App.xaml file:


this.RootVisual = new Page1();


You can change the above line to the class name of any oher xaml file to open that file by default.

Another scenario is, you may want to open different xaml files from the default xaml page. For example, consider that you have a xaml control that prompt user to enter login information. After the login credentials are validated, you may want to redirect to another xaml file when the user click the "Submit" button.

This can be done by setting the "Content" property of the xaml page.

private void SubmitButton_Click(object sender, RoutedEventArgs e)
{
        this.Content = new NewXamlPage();
}


The above code shows how to set the "Content" property of the xaml control in the button click event handler. When the user click on the submit button, the new xaml file (NewXamlpage) will be opened and original xaml file will be recycled.

Open a specific xaml page from a Silverlight control


This chapter shows how to open a specific xaml file from a Silverlight control which include multiple xaml pages.
Each Silverlight application project may include multiple xaml pages. When you refer to a .xap file from a web page, the xaml page set using the Application.RootVisual property will be displayed by default.

There may be cases where you want different XAML files to be displayed when you refer to the same .xap file from different web pages. You can do this by passing the xaml file name or some other kind of identification using InitParameters property of the Silverlight control. This property can be set to the Silverlight control from the web page. The value set from web page will be read by the Silverlight control and appropriate xaml page will be opened.

To demonstrate this, let us create a sample Silverlight project with the name "OpenSpecificXaml". (You can read the steps to create a new Silverlight project.)

After you compile and build your project, place the Silverlight control in your web page as shown below:



<asp:Silverlight 
    InitParameters="PageName=Page1"
    ID="Xaml1" 
    runat="server" 
    Source="~/ClientBin/OpenSpecificXaml.xap" 
    MinimumVersion="2.0.30923.0" 
    Width="100%" Height="100%" />


In the above code, see the code:


 InitParameters="PageName=Page1"


Here we are setting the property "InitParameters" with a key-value pair indicating which xaml page we want to open by default.

Now, we will read this property in the App.xaml file and set the appropriate page to the Application.RootVisual property. Here is the sample code to use in the App.xaml.cs to achieve this:


private void Application_Startup(object sender, StartupEventArgs e)
{
    IDictionary parameters = e.InitParams;

    if (parameters == null)
    {
        // No parameter passed.. open the default xaml
        this.RootVisual = new DefaultPage();
    }
    else if (parameters["PageName"] == "Page1")
    {
        this.RootVisual = new Page1();
    }
    else if (parameters["PageName"] == "Page2")
    {
        this.RootVisual = new Page2();
    }
    else 
    {
        // Open the default xaml
        this.RootVisual = new DefaultPage();
    }
}



Will be continued on.....


SilverLight

What is Silverlight?

Silverlight is a powerful cross-browser & cross-platform technology for building the next generation web experience & rich internet applications for the web. You can run Silverlight in most of all the popular browsers like Internet Explorer, Firefox, Chrome, Safari etc. Silverlight can run in various devices and operating systems like Windows, Apple Mac OS-X and Windows Phone 7. Using Silverlight you can create rich, visually stunning web applications like flash. Also you can create smooth animations using Storyboards; you can stream media over the net etc.
Silverlight web browser plug-in comes as free to install (approximately 4-5 MB in size). You can download the required plug-in from Microsoft Silverlight Site.


What are the System Requirements for installing Silverlight?

 
MINIMUM SYSTEM REQUIREMENTS FOR INSTALLING SILVERLIGHT PLUG-IN IS AS FOLLOWS:

PC Type
Processor
RAM
Operating System
Windows PC
500 MHz or higher, x86 or x64 bit processor
128 MB
Windows XP SP2+
Mac Power PC
PowerPC G4 800 MHz or higher
128 MB
Mac 10.4.8 or higher
Mac Intel-based
Intel Core Duo 1.83 GHz or higher
128 MB
Mac 10.4.8 or higher
Silverlight also supports Linux PCs. The plug-in name for Linux operating system is Moonlight and you can get the information about it in Mono Project's Moonlight site (http://www.mono-project.com/Moonlight).
MINIMUM SYSTEM REQUIREMENTS FOR INSTALLING SILVERLIGHT SDK FOR DEVELOPMENT IS AS FOLLOWS:
If you are a developer and want to start working on it, you must need the following environment to install the Silverlight tools.
Operating System
-     Microsoft Windows XP Service Pack 2 or higher
Developer Tools
-         Visual Studio 2008 SP1 (for Silverlight 3)
-         Visual Studio 2010 (for Silverlight 3 & Silverlight 4)
Designers Tools
-         Microsoft Expression Blend 3 (for Silverlight 3)
-         Microsoft Expression Blend 4 (for Silverlight 3 & Silverlight 4)
Silverlight SDK
-         Silverlight 3 Tools for Visual Studio 2008 SP1
-         Silverlight 4 Tools for Visual Studio 2010

How can I know whether Silverlight is installed in my PC?

If you are not sure whether Silverlight is already installed in your PC, just go to the Microsoft Silverlight Installation Page (http://www.microsoft.com/getsilverlight/get-started/install/) and that will tell you whether the plug-in is already installed or you need to install.


What are the Prerequisite to create a new Silverlight Application?
Before starting with the Silverlight application development be sure you have all the necessary softwares installed in your PC. If you don’t have then follow the steps mentioned in Microsoft Silverlight Site (http://silverlight.net/getstarted/) to download & install the following items in your development environment:
  • Visual Studio 2008 SP1 for Silverlight 3 application development or Visual Studio 2010 for Silverlight 3 & Silverlight 4 application development
  • Silverlight 3 Tools for Visual Studio 2008 SP1 or Silverlight 4 Tools for Visual Studio 2010
  • Expression Blend 3 for Silverlight 3 or Expression Blend 4 Preview for Silverlight 4 (optional)
  • WCF RIA Services for Silverlight (optional)
  • Silverlight 3 Toolkit or Silverlight 4 Toolkit based on your earlier version of Silverlight (optional)
Remember that, Silverlight 3 comes preinstalled with Visual Studio 2010 and hence if you are using Visual Studio 2010, you don’t need to install the Silverlight 3 Tools for it. Using Visual Studio 2010 you can develop both Silverlight 3 and Silverlight 4 applications but Visual Studio 2008 SP1 only supports Silverlight 3.
If you have proper development environment ready for Silverlight application you can proceed to the next chapter for creating our first simple Silverlight project. I am using Visual Studio 2010 RC and Silverlight 4 RC while writing these applications. Hence, the attached samples will not open in Visual Studio 2008.


What is XAML?

XAML stands for eXtended Application Markup Language. It is nothing but an XML file which is used to declaratively create the User Interface of the Silverlight or WPF applications. This XAML file generally rendered by the Silverlight plugin and displayed inside the browser window. When you compile your projects which includes XAML pages, those first converts into BAML (Binary Application Markup Language) and then rendered in the web browser window. Let use see a simple example of XAML here:
<TextBlock x:Name="txbTitle" Text="Hello Silverlight" FontFamily="Comic Sans MS" FontWeight="Bold"/>
The above XAML is a typical example where I am creating a text using the TextBlock control by specifying different properties as attributes to the control for name, font-family, weight, text etc.


What is App.xaml file?

App.xaml file is the loader of your Silverlight Application. You can declare your shared/global resources, styles, templates, different brushes inside this file which will be accessible by your application.
A typical App.xaml file looks like:
<Application 

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 

x:Class="SilverlightApps.HelloSilverlight.App">

<Application.Resources>
<!-- Brush -->
<SolidColorBrush x:Name="solidBrushRed" Color="Red"/>
<SolidColorBrush x:Name="solidBrushGreen" Color="Green"/>
<SolidColorBrush x:Name="solidBrushBlue" Color="Blue"/>
<!-- Styles -->
<Style x:Key="styleButton" TargetType="Button">
<Setter Property="Background" Value="Yellow"/>
</Style>
</Application.Resources>
</Application>
It has a code behind file too named as “App.xaml.cs”. This file is used to handle global application level events which you can use as per your need. Visual Studio creates these two files at the time of project creation. The three events inside the App.xaml.cs are:
  • Application_Startup
  • Application_Exit
  • Application_UnhandledException.
These three events are registered in the constructor of your App.xaml.cs file. Here is the code snippet of the same:

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 = newMainPage();
}private void Application_Exit(object sender, EventArgs e)
{ }private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (!System.Diagnostics.Debugger.IsAttached)
{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)
{ }
}
}

Let us do a brief discussion on each part of the code file.
Overview of App Constructor:
Inside the constructor of the App class you will find that all the three event has been registered. Also, there is a call to InitializeComponent() method. If you look around the whole class you will not find the method implementation. Strange!!! Where is the method?
The method has been implemented inside the partial class of the App class. If you go to the definition or just press F12 on top of the method, Visual Studio will open up the actual file named “App.g.i.cs” which contains the partial implementation of the same class. There you will find the method implementation.
What this method does: This method is responsible to load the XAML using the LoadComponent() method into the memory which can be used by your application.
What can we do inside the App.g.i.cs file: App.g.i.cs file is auto generated by the compiler and hence if you modify something there will be overwritten by the compiler itself on next build.
Why this file is not available inside my solution: As this is an compiler generated file, it has been placed inside the temporary directory named “obj”. If you go to the solution directory you will see the “obj” folder. Open it and browse through it’s subfolder (either debug or release) and you will see the file placed there. If you are unable to find it there, just do a rebuild of your solution and immediately it will be created there.
Overview of Application_Startup Event:
Application_Startup event is the root of your application. In this event you can create the instance of your initial page and set it as the RootVisual. Also, if you want to create some global objects or want to write some app initialization code, then this Application_Startup event will be the best part for you to implement it.
Overview of Application_Exit Event:
Similarly, you can write code to cleanup objects or do something when closing the application inside the Application_Exit event.
Overview of Application_UnhandledException Event:
If any exception comes while running and you didn’t handle that in the actual place, you can write some code in Application_UnhandledException to log the error details into database or show some message to the user. This will allow the application to continue running after an exception has been thrown. By default, if the app is running outside of the debugger then report the exception using the Browser DOM & the error will be visible in the status bar of Internet Explorer.


What is MainPage.xaml file?

When you create the Silverlight project, Visual Studio IDE will automatically add a default “MainPage.xaml” file which is actually a startpage for your Silverlight application. You can modify this page as per your need or can create a new one. So, what’s there inside the file? Lets look at it:
<UserControl x:Class="SilverlightApps.HelloSilverlight.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>
Lets walk-through each lines of the code. It contains an UserControl as root of the file which may contain all other controls inside it. The following line tells the compiler to use the specified class to use:
x:Class="SilverlightApps.HelloSilverlight.MainPage"
The next couple of lines beginning with xmlns tells the compiler to import some namespaces which can be used by the Silverlight XAML page.
The following line speaks about the design time Height & Width of the Silverlight page:
d:DesignHeight="300" d:DesignWidth="400"
If you want to specify actual Height & Width of your Silverlight application, you can manually append the following line inside that:
Height="300" Width="400"
Next comes the Grid control which is used as a layout panel and that can include more other controls. Though the default XAML file uses the Grid as the layout panel, you can change it to any other panel as per your need. I will discuss about the various panel later in this tutorial.
<Grid x:Name="LayoutRoot" Background="White">

</Grid>
“MainPage.xaml” has also it’s code behind file like App.xaml & you can use this to write code to develop your functionalities. By default, it comes empty with a call to Initialize() method inside the Constructor of the MainPage class. The implementation of this method is also available in a different partial class of MainPage inside “MainPage.g.i.cs” like “App” class. Whenever you add some controls inside the XAML page, it will be loaded here.


What is XAP file?

XAP (pronounced as ZAP) is the compressed output of the Silverlight Application which includes application manifest file, compiled output assembly and other resources used by your silverlight application. This uses the normal ZIP compression method to reduce the total download size. When you build your Silverlight application, it actually generates this .XAP file & puts in the output folder which the .aspx page refers as source to load the application.
Once you build your project, it will create the XAP file (in our case, it is: SilverlightApps.HelloSilverlight.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.

How can I host a Silverlight Application?

When you create a Silverlight project, it asks you to create a Web Application project. This project is responsible for hosting your XAP file. Generally Silverlight application doesn’t require any server to host it to run, but if you are planning to host it in web you must need a web server for that.
Once you publish your Web Application to host in IIS, you may need to add three MIME types in your IIS Server. This is require to host it in earlier versions of IIS. Latest version of IIS comes with that configuration by default. Followings are the list of MIME Types those you need to add in your IIS Properties:
  • .xap       application/x-silverlight-app
  • .xaml      application/xaml+xml
  • .xbap     application/x-ms-xbap
Silverlight Application (XAP) generally loads inside the ASPX or HTML pages pointing to the path to load the XAP. The aspx/html page uses <object /> tag to load the Silverlight application.
Here is the code present inside the aspx/html pages for loading the Silverlight XAP:
<object data="data:application/x-silverlight-2," 

type="application/x-silverlight-2" width="100%" height="100%">
<paramname="source" value="ClientBin/SilverlightApps.HelloSilverlight.xap"/>
<paramname="onError" value="onSilverlightError" />
<paramname="background" value="white" />
<paramname="minRuntimeVersion" value="4.0.50222.0" />
<paramname="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50222.0"
style="text-decoration:none">
<imgsrc="http://go.microsoft.com/fwlink/?LinkId=161376"
alt="Get Microsoft Silverlight" style="border-style:none"/>
</a>
</object>
Let us go line by line to learn the basics of it.
  • In the first line <object> tag tells the browser to load the Silverlight plug-in.
  • Next couple of lines uses <param> tag.
    • The first param “source” has the value to the location of the .xap file.
    • Second param “onError” tells the plug-in to call the javascript method mentioned in the value, if any application error occurs.
    • The third param “background” specifies the color of the Silverlight application background.
    • The next param “minRuntimeVersion” specifies the minimum required plug-in version to load your Silverlight application.
    • If “autoUpgrade” is set as true in the next param, it will automatically upgrade the runtime.
  • The next lines are very interesting. Whatever you design there, will not be visible in the browser in normal scenarios. If the user doesn’t have Silverlight runtime installed in his PC or the Silverlight plug-in is disabled this section will visible to the user. This part is well known as “Silverlight Installation Experience panel”. By default, it shows a Silverlight image to download the runtime from Microsoft site. When the user clicks on it, this starts the installation. I will discuss about the Silverlight Experience later in depth. 

How to create a new Silverlight Project?

If your development environment is ready then we can proceed towards creating a new Silverlight Application project. At the end of this part we will be able to run our first Silverlight application inside the browser.
1. Open your Visual Studio 2010 IDE
2. Select File > New Project or just press CTRL + SHIFT + N to open up the New Project dialog
3. Expand the “Visual C#” node and then go to sub node “Silverlight”
4. Select “Silverlight Application” in the right pane

Create new project
Figure 1: Visual Studio Project Types

5. Select proper location to store your application (let’s say, “D:\Sample Apps\”
6. Now enter a proper name for your project (call it as: SilverlightApps.HelloSilverlight)
7. Select the .Net Framework version from the combo box at the top (I am using .Net Framework 4.0 by default as I am using Visual Studio 2010) and click OK
8. In the next dialog make sure that “Host the Silverlight application in a new Web site” option is selected

create new silverlight application
Figure 2: Silverlight Hosting Application

9. Choose “Silverlight 4” as the Silverlight Version and hit OK

Wait for a while, Visual Studio will now create the first Silverlight solution for you to use which will contain a Silverlight Project and one Web Application Project to host your Silverlight application. Once done, you will see Visual Studio already created two XAML files (App.xaml & MainPage.xaml) for you inside the Silverlight Application project.
So for now your first Silverlight application has been created. Press F5 to run the application. It will open a browser Window with a blank page on that. Wow! What happened? Nothing is there!!! Don’t worry, everything is fine. We didn’t modify the default blank XAML page. Just right click on the browser page & you will see the Silverlight context menu on that.

first silverlight page
Figure 3: Silverlight inside the Browser


What’s the Project Structure of Silverlight?


When you create a new Silverlight project, Visual Studio IDE creates two different projects for you (as you can see in the below picture). One is your main Silverlight project and the another is a Web application project which will host your Silverlight application (.xap file).

Silverlight project structure
Figure 4: Silverlight Project Structure

The main Silverlight project (SilverlightApps.HelloSilverlight) consists of App.xaml, App.xaml.cs, MainPage.xaml & MainPage.xaml.cs. I already discussed on those file in depth in previous chapter. The web project (SilverlightApps.HelloSilverlight.Web) consists of JavaScript file named Silverlight.js which is responsible for checking the Silverlight version in client side and also if the Silverlight plug-in is missing at the user end, it asks to install the required runtime from Microsoft site. The .aspx & .html pages are present in the root to host the Silverlight application. Your Silverlight application .xap file is located under the ClientBin directory inside the Web project.


Creating a “HelloSilverlight” Application


Now let us start modifying the “MainPage.xaml” by insertinga text “Hello Silverlight”. We will add one TextBlock control inside the Grid panel with it’s text property as “Hello Silverlight”.
But before going to add the content inside your page let me tell you that, you can add it in two ways: “Declarative approach in XAML” and “Programmatic approach in Code-Behind”. In declarative approach you have to add the Silverlight controls in the XAML page in XML format only with their properties as attributes. In other hand, you have to create the objects of the controls programmatically and have to set their properties.
First go with the Declarative Approach:

1. Open the file “MainPage.xaml” in Visual Studio
2. Inside the Grid tag add the following texts:
<TextBlock x:Name="txtTitle" Text="Hello Silverlight From XAML" FontSize="32" Foreground="Red" HorizontalAlignment="Center"/> 
Your XAML page will now look like this:
<UserControl x:Class="SilverlightApps.HelloSilverlight.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">
<TextBlock x:Name="txtTitle" Text="Hello Silverlight From XAML"
FontSize="32" Foreground="Red" HorizontalAlignment="Center"/>
</Grid>
</UserControl>
3. Press F5 to run your application once again. Once the browser loads your Silverlight application you will see “Hello SilverlightFrom XAML” text appears inside the browser window.

First silverlight application
Figure 5: Hello Silverlight from XAML in Browser

Now, we will create the same from the code behind (programmatically). Assume that, we have not added the Text inside the XAML.
1. Open your “MainPage.xaml.cs” using the Visual Studio
2. There you will find the constructor of the MainPage class. Add the following lines of code after the call to the InitializeComponent() method:

// Create the instance of the textblock and set it's propertiesTextBlock txtTitle = new TextBlock

{
Name = "txtTitle",
Text = "Hello Silverlight From Code",
FontSize = 32.0,Foreground = new SolidColorBrush(Colors.Red),
HorizontalAlignment = HorizontalAlignment.Center
};
// Add the textblock instance as the children of the "LayoutRoot" LayoutRoot.Children.Add(txtTitle);

Let’s describe it in depth. First of all we are creating the instance of the TextBlock control and setting the Name, Text, FontSize, Foreground color etc. at the time of initialization. Then once the control is ready, we are adding it to the main panel i.e. the Grid layout panel inside the XAML named “LayoutRoot”.
After adding this your code will look like below:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace SilverlightApps.HelloSilverlight

{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();// Create the instance of the textblock and set it's properties
TextBlock txtTitle = new TextBlock
{
Name = "txtTitle",
Text = "Hello Silverlight From Code",
FontSize = 32.0,Foreground = new SolidColorBrush(Colors.Red),
HorizontalAlignment = HorizontalAlignment.Center
};// Add the textblock instance as the children of the "LayoutRoot"
LayoutRoot.Children.Add(txtTitle);
}
}
}

3. Press F5 to run your application. You will now see your browser window opens with a text “Hello Silverlight From Code” inside it.

Hello Silverlight from Code in Browser
Figure 6: Hello Silverlight from Code in Browser

Note that, the TextBlock control has been added as a child element to the LayoutRoot panel which is a Grid. So, the question here is, what are the panels available in Silverlight where we can add child controls? Ok, for now just remember that there are several content holders (panels) available to hold any child controls like: Grid, Canvas, Border, StackPanel etc. In XAML pages the elements are maintained in a hierarchy like the HTML pages (DOM i.e. Document Object Model). This hierarchy allows us to nest different controls inside each other. I will discuss on this in depth in the next chapter.


Creating a Silverlight UserControl


In our last example we have seen, once we created the Silverlight project, the Visual Studio IDE has automatically created two XAML pages: App.xaml&MainPage.xaml. If you view the MainPage.xaml in depth, you will notice that it started with “UserControl” as the root element.
<UserControl x:Class="SilverlightApps.HelloSilverlight.MainPage"

. . . >

</UserControl>
Also, if you open the MainPage.xaml.cs file you will notice that the class itself inherits from the base class “UserControl”.
namespace SilverlightApps.HelloSilverlight

{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
}
}

So, what is that UserControl? UserControls are basic unit of reusable XAML like you use in asp.net. It is the root of your XAML and contain only one child as a control. Though that child may contain one or more other controls but the UserControl must have a maximum of one content control. UserControls are mainly created using XAML and then reused in various places.
How can I create a simple new Silverlight UserControl? Is it difficult to implement? Ummm… I will not tell you. Let us create a simple UserControl then. You will tell me whether it is difficult or simple.


Silverlight Tools for Visual Studio comes up with the default template for creating a basic UserControl. Now follow the steps to create it:
  1. Open your existing Silverlight application project (for this example, you can use the “HelloSilverlight” project just now we created)
  2. Right click on the Silverlight project “SilverlightApps.HelloSilverlight” and select Add -> New Item
  3. Select “Silverlight UserControl” from the right panel
  4. Enter a good name (here I am using “EmployeeView”) and hit enter

Silverlight UserControl Creation
Figure 7: Silverlight UserControl Creation

This will create the UserControl named “EmployeeView” with the default template layout and open up the XAML page in the IDE. If you look into the XAML code you will notice the following code:

<UserControl x:Class="SilverlightApps.HelloSilverlight.EmployeeView"

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>
We already discussed about each of the lines in the previous chapter (in “What is MainPage.xaml file” section). So, I will not cover it again. Now let us build our first UserControl to show the Employee’s FirstName, LastName& Department inside the UserControl XAML file. How to do that? Before doing it let us split our Grid panel into three Rows & two Columns (will discuss on this in next chapter):

<Grid x:Name="LayoutRoot" Background="White">

<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
Now, lets add the TextBlocks inside the Grid, in specific Rows and Columns. In our case the left column will hold the “FirstName”, “LastName” and “Department” label. The second column will hold the informations according to the labels. Here is the XAML code for the same:

<UserControl x:Class="SilverlightApps.HelloSilverlight.EmployeeView"

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" Width="300">

<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="LabelFirstName" Text="FirstName" Grid.Row="0" Grid.Column="0"/>
<TextBlock x:Name="FirstName" Text="Kunal" Grid.Row="0" Grid.Column="1"/>
<TextBlock x:Name="LabelLastName" Text="LastName" Grid.Row="1" Grid.Column="0"/>
<TextBlock x:Name="LastName" Text="Chowdhury" Grid.Row="1" Grid.Column="1"/>
<TextBlock x:Name="LabelDepartment" Text="Department" Grid.Row="2" Grid.Column="0"/>
<TextBlock x:Name="Department" Text="Software Engineering" Grid.Row="2" Grid.Column="1"/>
</Grid>
</UserControl>
You can see, I am using “Grid.Row” and “Grid.Column” attributes in each TextBlock. What does it mean? Grid.Row specifies the row number where to place the control. Similarly, Grid.Column specifies the column number. For example, if you use Grid.Row=”2” and Grid.Column=”4” to any element inside your Grid, the element control will be placed in 3rd Row and 5th Column of the Grid. You can think the Grid panel as a Matrix which has zero based index.
Our UserControl is ready now, but before running the application we need to put it inside the MainPage which loads at application load. You can do this in two different ways. One is using the XAML and the another is using the Code-behind file. In code behind it is very easy. You have to follow the same steps as we did in previous chapter to set the “Hello Silverlight” TextBlock, but if you want to set it in XAML you have to do a little trick for the first time. Let us discuss on this step-by-step:

First go with the Declarative Approach:
1. Open the file “MainPage.xaml” in Visual Studio
2. Add the following line inside the UserControl tag of the MainPage.xaml (after any xmlns line):
xmlns:uc="clr-namespace:SilverlightApps.HelloSilverlight"
Now, your MainPage.xaml will look like this (the bolder text I have inserted in the XAML):
<UserControl x:Class="SilverlightApps.HelloSilverlight.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"

xmlns:uc="clr-namespace:SilverlightApps.HelloSilverlight"

mc:Ignorable="d"

d:DesignHeight="300" d:DesignWidth="400">

<Grid x:Name="LayoutRoot" Background="White">
</Grid>
</UserControl>
Here, “uc” stands for pre-tag for specifying the namespace. You can use any name. We used “uc” to specify “UserControl” for better readability. Now inside the Grid control you can add the UserControl we have just created. Here is the code for the same:

<Grid x:Name="LayoutRoot" Background="White">

<uc:EmployeeView Width="300" Height="60"/>

</Grid> 
Once you run your application now, you will see the following view of your first UserControl application:
First UserControl View
Figure 8: First UserControl View

Now let us create it from Code-behind. I assume that the control we just added inside the Grid has been removed from the XAML, that means your Grid panel has no child inside it. Create the instance of the EmployeeViewUserControl and add it as child to the LayoutRoot Grid:
// Create the instance of the EmployeeViewUserControlEmployeeView empView = new EmployeeView

{

Width = 300.0,
Height = 60.0,
};
// Add the EmployeeViewUserControl as the child of the default panel "LayoutRoot"LayoutRoot.Children.Add(empView);

Run your application and you will see the same output. The second approach is easy, am I right? Yup, for the first application it looks very easy enough. But when you write complex applications you will notice that the first approach is easier than the later. Why? Because, you will get more control over the design. You can see the output immediately in the preview sceen, also you can drag the control to position it properly in the panel. In some cases you will find it useful from code.  Depending upon your business need you have to decide where to create and add your UserControl.
Is it confusing? No, when you are sure that you have to dynamically load no. of UserControls based on your data you have to create and load it from the code behind. For the other cases, it will be easier to write inside the XAML.
Remember that, you can create as many instances of your UserControl and place it inside your XAML page. Once we discuss on the different types of panel and layout in next chapter you can get better visibility to that.

Overview of Panels

There are total six numbers of panels available in Silverlight. They are as below:
  1. Grid
  2. Canvas
  3. StackPanel
  4. ScrollViewer
  5. Border
  6. ViewBox
You will find Grid, Canvas, StackPanel and Border as most useful panel while you start working with them in your Silverlight application. Let us discuss about those in depth.

“Grid” Layout Panel

The Grid layout panel is the most useful panel you ever use. This is the default panel inserted inside every xaml when you create a UserControl. When we created our first Silverlight example or even the first UserControl, you noticed that there was a Grid panel named “LayoutRoot” where we created Rows and Column definitions to place our control to create the Employee View.
The Grid layout control allows you to define the Grid structure to place individual elements as Rows & Column structure in Matrix format. Once you divide your Grid panel in Rows and Columns you can place your element in the appropriate cell by using Grid.Row or Grid.Column property.

See the Grid structure in the below image:
Grid layout panel
Picture: Grid Layout Panel Structure

Now lets discuss about creating rows and columns, then place some rectangles in each cells. We will create three rows and three columns as described in the above image:
1. Create a UserControl named “GridPanelDemo” in our Silverlight Application.
2. Open the GridPanelDemo.xaml file. You will see that there is a Grid named “LayoutRoot” inside your UserControl.
3. Now enter the following XAML code between the Grid tags (<Grid>…</Grid>):
<Grid.RowDefinitions>

<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
4. This will divide your Grid in three rows and three columns of equal height and equal width.
5. You can also set height for Rows and widths for Columns by specifying the value to the properties like this:
<RowDefinition Height="100"/> 

and 

<ColumnDefinition Width="100"/>
6. You can specify the value for Height & Width in three different ways:
a. Pixel Value (like: “90”, means the height or width of 90 pixel)
b. Percentage Value (like: “5*”, means the height or width of 50% or “*”, means 100%)
c. Automatic Value (like: “Auto”, means the height or width of the Row or Column will resize automatically as  per the size of content of the respective Row or Column.
7. Now we will put some texts using TextBlock and will put them in appropriate cells of the Grid control. You can achieve this by using the Grid.Row=”ROW_NUMBER” and Grid.Column=”COLUMN_NUMBER” as the property of your TextBlock control. Modify your XAML to set this texts like this:
<Grid x:Name="LayoutRoot" Background="BlanchedAlmond">

<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="Row[0], Col[0]" Grid.Row="0" Grid.Column="0" />
<TextBlock Text="Row[0], Col[1]" Grid.Row="0" Grid.Column="1" />
<TextBlock Text="Row[0], Col[2]" Grid.Row="0" Grid.Column="2" />
<TextBlock Text="Row[1], Col[0]" Grid.Row="1" Grid.Column="0" />
<TextBlock Text="Row[1], Col[1]" Grid.Row="1" Grid.Column="1" />
<TextBlock Text="Row[1], Col[2]" Grid.Row="1" Grid.Column="2" />
<TextBlock Text="Row[2], Col[0]" Grid.Row="2" Grid.Column="0" />
<TextBlock Text="Row[2], Col[1]" Grid.Row="2" Grid.Column="1" />
<TextBlock Text="Row[2], Col[2]" Grid.Row="2" Grid.Column="2" />
</Grid>
8. Also, you can use Grid.RowSpan and Grid.ColumnSpan properties to span your rows and columns. If you are familiar with HTML table tag & properties you can easily understand it properly.
<TextBlock Text="Row[0], Col[0]" Grid.Row="0" Grid.Column="0" Grid.RowSpan="2" Grid.ColumnSpan="2" /> 
If we use the above code, it will span the 0th Row and 0th Column to two Rows & Columns. This is nothing but merging rows and columns of Grid Layout.
9. Now, open the MainPage.xaml.cs file & in the constructor create the instance of the GridPanelDemo usercontrol and add it as the child of the LayoutRoot i.e. Grid.
LayoutRoot.Children.Add(new GridPanelDemo());
10. Run your Silverlight application. You will see that, the TextBlocks are arranged in the Page in matrix manner.
Grid Layout Panel
Picture: Grid Layout Panel Demo

You will find this useful when you have to position your controls in proper way, in proper Row & Column. Note that, if you don’t create rows or columns and place multiple controls inside your naked Grid, you will see them overlapping each other. So, if you are using Grid be sure that you splitted your Grid in proper rows and columns.

“Canvas” Layout Panel

Canvas is the simplest layout available in Silverlight. It is very easy to understand and using this you can place any content any where inside the canvas. Not only this, you can also layered your application and by layering you can put your content front or back of any other control.
You can think Canvas as a HTML div Tag, where you can put your content in specific location by providing absolute left and top position. Have a look into the below image to get a brief idea on the same.

Canvas Panel
Picture: Canvas Layout Panel Structure

Lets think there are two Rectangles placed inside the Canvas as mentioned in the above figure. The first Rectangle (Blue one) is placed at the (10, 10) position. This is the coordinate location of your first Rectangle. First one stands for “Left” and second one stands for “Top”. So, What is the coordinate position of the second Rectangle (Orange one)? Exactly, it is Left =50 and Top = 30 i.e. (50, 30).

I think it is the right time to go for writing a sample code to create the above canvas with two Rectangles inside it. I am pretty much confident that, you have now a good confidence on the Canvas positioning.
Let us create a new UserControl named “CanvasPanelDemo” and then we will create two Rectangles in it and will place it in proper location.
1. Create a UserControl named “CanvasPanelDemo” in our Silverlight Application.
2. Open the CanvasPanelDemo.xaml file. You will see that there is a Grid named “LayoutRoot” inside your UserControl.
3. Now replace your Grid tag (<Grid>…</Grid>) with a Canvas tag (<Canvas>…</Canvas) and set the background color as Green:
<Canvas Background="Green" >

</Canvas>
4. Now, open your MainPage.xaml.cs file and modify your constructor to load the newly created CanvasPanelDemo Usercontrol in page load as a child to your LayoutRoot Grid:
LayoutRoot.Children.Add(new CanvasPanelDemo());
5. If you run your application now, you will see that your Canvas has taken the full screen of your browser window. Why? You didn’t set the Height & Width of your UserControl and placed inside a Grid. That’s why it took the full size of the browser window and that’s why you can see your Green canvas taking the whole screen.
6. We will now create two Rectangles and place it inside the Canvas. For the first time, we will not set any position to the rectangles. Lets see what happens then. Modify your XAML to look like this:
<Canvas Background="Green" >

<Rectangle x:Name="rectFirst" Fill="Blue" Height="80" Width="120"/>
<Rectangle x:Name="rectSecond" Fill="Orange" Height="100" Width="150"/>
</Canvas>
7. If you run your application again, you will see only one Rectangle present inside your Canvas. Which one? Yes, only the orange one. So, there you will ask “We added two Rectangle, one Green and another Orange. But why only the orange one is visible in the UI? What happened to the first rectangle?” So, my answer will be “Nothing happened to any of your added control. They all are placed inside the Canvas”.
Yes, that’s right. All the two rectangles are available inside your canvas. As we didn’t specify the position of the rectangles and the second rectangle is bigger than the first one, it placed on top of the other i.e. the orange one placed on top of the green rectangle. Whatever control you add at the end of the Canvas will have a higher Z-Index which places your control on top of the other. I will discuss on this later in this chapter.

Canvas Panel
Picture: Canvas Panel Demo 1 (without position)

8. Now, lets go for positioning the rectangles. We will set coordinate position (50, 50) to the first rectangle and coordinate position (200, 100) to the second rectangle. For doing this, we have to set the Canvas.Left and Canvas.Top properties of each Rectangle. Have a look into the following code. You will understand easily how to do this.
<Canvas Background="Green">

<Rectangle x:Name="rectFirst" Fill="Blue" Height="80" Width="120"
Canvas.Left="50" Canvas.Top="50" />
<Rectangle x:Name="rectSecond" Fill="Orange" Height="100" Width="150"
Canvas.Left="200" Canvas.Top="100" />
</Canvas>
9. Run your application and you will notice that the first rectangle has been placed at (Left=50, Top=50) location and the second one has been placed at (Left=200, Top=100) location. Your application will look similar to this:
Canvas Panel with proper position
Picture: : Canvas Panel Demo 2 (with proper position)

10. Now if you want to play around it, just modify your XAML to place the rectangle controls in various positions inside the canvas.

I think you are now familiar with positioning silverlight controls inside the Canvas. Let us discuss something on the Z-Index property. Z-Index stands for layering out your Silverlight application. If you are familiar with Photoshop you knew that, photoshop creates layers to position them on top of each other. Those who don’t know about it can learn it from here.
Suppose you want to create an application where two rectangles are there (similar to the previous example) and one rectangle is partially blocking the another. You have to write a logic to modify your application such that, when you click on the first rectangle it will come front of the another. Similar kind of logic for the second rectangle too.

So, how can we develop this? We have to use the Z-Index property for each rectangle. Lets say we will set the Z-Index of the first rectangle to 1 (one) and the second rectangle to 2 (two). Initially the second rectangle is blocking the first one partially. Now once you click on the first rectangle we will set the Z-Index of it to 2 and the Z-Index of the other rectangle to 1. As the Z-Index of the first rectangle is greater than the second it will come on top of the other. The same behaviour will be for the second rectangle. Once we click on the second rectangle (which is hiding behind the first) will come top the other will go behind. For doing this, we will set the Z-Index of the first rectangle to 1 and the second to 2.


1. Open the CanvasPanelDemo.xaml file and modify the Rectangle properties of Canvas.Left and Canvas.Top to place the rectangle on top of each other.
2. Now add the Canvas.ZIndex property to each rectangle. Set it to 1 for the first rectangle and set it to 2 for the second rectangle. After these modifications your xaml will look like this:
<Canvas Background="Green">

<Rectangle x:Name="rectFirst" Fill="Blue" Height="80" Width="120"
Canvas.Left="50" Canvas.Top="50" Canvas.ZIndex="1" />
<Rectangle x:Name="rectSecond" Fill="Orange" Height="100" Width="150"
Canvas.Left="92" Canvas.Top="74" Canvas.ZIndex="2" />
</Canvas>
3. Run your Silverlight application and you will see them in action. You will see the orange rectangle blocking a part of the blue rectangle.

Canvas Panel Demo
Picture: Panel Demo (ZIndex - 1)

4. Now let us write some logic to code behind (C#) to change the ZIndex property of the rectangles. To do this, first we will register the MouseLeftButtonDown event of both the rectangles in the constructor:
public CanvasPanelDemo()

{

InitializeComponent();
rectFirst.MouseLeftButtonDown += (rectFirst_MouseLeftButtonDown);
rectSecond.MouseLeftButtonDown += (rectSecond_MouseLeftButtonDown);
}
5. Now in the MouseLeftButtonDown event of the first rectangle we will set the ZIndex of the first rectangle to 2 and the second rectangle to 1. This will cause the first rectangle to come on top of the second rectangle.
private void rectFirst_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)

{
Canvas.SetZIndex(rectFirst, 2);
Canvas.SetZIndex(rectSecond, 1);
}
6. In the MouseLeftButtonDown event of the second rectangle we will set the ZIndex of the first rectangle to 1 and the second rectangle to 2. This will cause the second rectangle to come on top of the first one.
private void rectSecond_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)

{
Canvas.SetZIndex(rectFirst, 1);
Canvas.SetZIndex(rectSecond, 2);
}
7. Run your application to see it in action. At the initial time the second rectangle will be on top of the first one. When you click on the first rectangle it will come in front. Once you click on the second rectangle the first will go behind and thus the second rectangle will come at the front.
Canvas Panel Demo - ZIndex 2
Picture: Canvas Panel Demo (ZIndex - 2)

Canvas Panel Demo (ZIndex - 3)
Picture: Canvas Panel Demo (ZIndex - 3)


“StackPanel” Layout Panel

StackPanel is one of the most important panel in Silverlight. You will find it useful when you want to show some of your Silvelright elements either Horizontally or Vertically. It has a property called “Orientation”. You can set it appropriately as per your requirement.
Once you add some elements inside StackPanel, you will notice that they will place as a Stack on top of each other. Have a look into the following figure to get a clear understanding of the same.


Picture: StackPanel Orientation (Horizontal & Vertical)

Let us create an example to showcase the StackPanel demo:
1. Create a UserControl named “StackPanelDemo” in your Silverlight project
2. Now, open your MainPage.xaml.cs file and modify your constructor to load the newly created StackPanelDemo Usercontrol in page load as a child to your LayoutRoot Grid:
LayoutRoot.Children.Add(new StackPanelDemo());
3. Open the StackPanelDemo.xaml file and inside the Grid tag named “LayoutRoot” we will add two StackPanels (one Horizontal and another Vertical) with some Rectangles as Children.
4. The following XAML code will create a Vertical StackPanel which consists of four rectangles of different colors:
<StackPanel Orientation="Vertical" Background="SkyBlue" Height="200" 

Width="100" Grid.Column="0">

<Rectangle Height="50" Width="100" Fill="Red" />
<Rectangle Height="50" Width="100" Fill="Green" />
<Rectangle Height="50" Width="100" Fill="Blue" />
<Rectangle Height="50" Width="100" Fill="Yellow" />
</StackPanel>
5. The following code will create a Horizontal StackPanel which also contains four rectangles of different colors:
<StackPanel Orientation="Horizontal" Background="SkyBlue" Height="100" 

Width="300" Grid.Column="1">

<Rectangle Height="100" Width="60" Fill="Red" />
<Rectangle Height="100" Width="60" Fill="Green" />
<Rectangle Height="100" Width="60" Fill="Blue" />
<Rectangle Height="100" Width="60" Fill="Yellow" />
</StackPanel>
6. Now run your application and you will notice the following UI of your StackPanel Demo application. The left panel is your Vertical StackPanel whereas the right panel is the Horizontal StackPanel.
StackPanel Demo
Picture: StackPanel Demo


“ScrollViewer” Layout Panel


ScrollViewer is another layout container, which you will find interesting in some cases. Though it is not require to use in all the scenarios to hold elements but to show contents inside a scrollable panel like ListBox or Editor window you have to use ScrollViewer. ListBox, TextBox, RichTextBox internally uses ScrollViewer to implement the scrolling functionality.
Now come the question of implementing the scrollviewer functionality to our previous sample of StackPanel demo. If you add more Rectangles in the Vertical StackPanel in the previous demo application, you will notice that the rectangles are cropping inside the StackPanel as it has a fix height of 100. Now do the following to implement the scrolling functionality in the Vertical StackPanel:
1. Open the StackPanelDemo.xaml file to edit our previous XAML file
2. Remove the Height & Grid.Column properties from the StackPanel
3. Surround the StackPanel with ScrollViewer tag (<ScrollViewer> … </ScrollViewer>) and set the Height of the ScrollViewer to 200. Also add the Grid.Column = “0” to the ScrollViewer.
4. Add some more rectangles inside the StackPanel, so that, the ScrollBar got enabled for the ScrollViewer. After the modification of your XAML will look like this:
<ScrollViewer Height="200" Grid.Column="0">

<StackPanel Orientation="Vertical" Background="SkyBlue" Width="100">
<Rectangle Height="50" Width="100" Fill="Red" />
<Rectangle Height="50" Width="100" Fill="Green" />
<Rectangle Height="50" Width="100" Fill="Blue" />
<Rectangle Height="50" Width="100" Fill="Yellow" />
<Rectangle Height="50" Width="100" Fill="Red" />
<Rectangle Height="50" Width="100" Fill="Green" />
<Rectangle Height="50" Width="100" Fill="Blue" />
<Rectangle Height="50" Width="100" Fill="Yellow" />
<Rectangle Height="50" Width="100" Fill="Red" />
<Rectangle Height="50" Width="100" Fill="Green" />
<Rectangle Height="50" Width="100" Fill="Blue" />
<Rectangle Height="50" Width="100" Fill="Yellow" />
</StackPanel>
</ScrollViewer>
5. If you run the application now, you will see a ScrollBar on the right side of the panel. Thus it make your Rectangles to scroll properly.
ScrollViewer Panel Demo
Picture: ScrollViewer Panel Demo

Here note that, we set the Height to the ScrollViewer and not to the StackPanel. The reason behind this is, if you set the Height of the StackPanel it will have a fix height, thus it will not create the Scrolling behaviour. As we set the Height to the ScrollViewer the StackPanel height increases as and when you add child to it but the ScrollViewer here does a great job and creates a scrollbar cropping the StackPanel to the height of the ScrollViewer.


“Border” Layout Panel

It’s an another type of Layout Panel in Silverlight. But as like other panels it can’t contain multiple contents in it. Border supports only one child as a content. If you want to use Border as a container of multiple controls, you have to wrap those with anyother panel like Grid, Canvas etc. and then place it in the Border. So, what is Border actually? The name says it. It is a border. If we want to add some border in our Silverlight application, we can use it at that time.
Look into the following figure. Here you will see four different shapes. These shapes you can create using Border element. You can create your border filled with Solid color or Gradient color or you can use a transparent color.


Border Panel Example
Picture: Border Panel Example

After seeing the above figure, I think one question came to you mind that “I can create the same thing using the Rectangle too. Then what is the benefit of using Border?” Yes right. You can create the same thing using Rectangle too as we did earlier, but the main difference is “You can create a rounded corner shape using Border. It has the property called “CornerRadius”. If you set it to 45, means your shape will have a corner radius of 45 degree.
Let us create some borders in a demo application:
1. Create a UserControl named “BorderDemo” in your Silverlight project
2. Now, open your MainPage.xaml.cs file and modify your constructor to load the newly created BorderDemo Usercontrol in page load as a child to your LayoutRoot Grid:
LayoutRoot.Children.Add(new BorderDemo());
3. Open the BorderDemo.xaml file and inside the Grid tag named “LayoutRoot” we will add a Border as Content.
4. Let us add the first Border of Height=100 and Width=150 with a brown colored BorderThickness of 2:
<Border Height="100" Width="150" BorderThickness="2" BorderBrush="Brown"/>
Once run in browser you will see the following view:

Border Panel Demo 1
Picture: Border Panel Demo 1

5. Now we will modify this border to create a Rounded Corner border. To do this, we will add a property “CornerRadius” to it. We will set the value to 25 i.e. 25 degree. Your modified XAML will look like this:
<Border Height="100" Width="150" CornerRadius="25" BorderThickness="2" BorderBrush="Brown"/> 
Border Panel Demo 2
Picture: Border Panel Demo 2

6. Now we will change it a little to set a background color to it. Border has a property called “Background”. You can set the color there which you like. Here is the modified XAML of the same:
<Border Height="100" Width="150" CornerRadius="25" BorderThickness="2" BorderBrush="Brown" Background="Brown"/> 
If you run your Silverlight application now, you will see the following:
Border Panel Demo 3
Picture: Border Panel Demo 3

7. Let us modify it a little bit more to add a child inside it. We will put a Text “I am a TextBlock inside Border control”. Put the below code in your XAML. You will notice that I placed a TextBlock inside the <Border> … </Border> tag. You can place any control or panel inside the Border like this.
<Border Height="100" Width="250" CornerRadius="25" BorderThickness="2" BorderBrush="Brown" Background="Brown">

<TextBlock Text="I am a TextBlock inside Border control"
VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Border>
Once you run, it will show similar to this:
Border Panel Demo 4
Picture: Border Panel Demo 4

Remember that, you can add only one child to the Border panel. If you need to add more than one child, add a different panel like Grid, Canvas or StackPanel inside the Border and then add the child elements to that panel. Think before chosing your panels.


“ViewBox” Layout Panel

ViewBox panel is another useful panel in Silverlight. It is actually not a new panel in Silverlight. It was available in Silverlight 3 toolkit, but Microsoft added it in the Silverlight 4 runtime for it’s demand. You can use ViewBox panel to stretch and scale a element control. Like Border it also has only and only one child. If you want to set more than one child, you have to use any other panel inside the ViewBox to hold other children controls.
As I told earlier, you can stretch and scale your control inside your ViewBox. It has a property called “Stretch” which has the following values:

1. Fill:
If you set the Stretch property to Fill, the content will fill the entire space of the ViewBox. It doesn’t preserve the aspect ratio.
<Viewbox Stretch="Fill" MaxWidth="100" MaxHeight="100" Name="viewBox1">

<Image Source="images/microsoft_silverlight.jpg"/>
</Viewbox> <Viewbox Stretch="Fill" MaxWidth="200" MaxHeight="200" Name="viewBox2">
<Image Source="images/microsoft_silverlight.jpg"/>
</Viewbox> <Viewbox Stretch="Fill" MaxWidth="300" MaxHeight="300" Name="viewBox3">
<Image Source="images/microsoft_silverlight.jpg"/>
</Viewbox>

//Set the Stretch property to Fillprivate void stretchFill(object sender, RoutedEventArgs e)

{
viewBox1.Stretch = Stretch.Fill;
viewBox2.Stretch = Stretch.Fill;
viewBox3.Stretch = Stretch.Fill;
}

ViewBox Demo 1
Picture: ViewBox Demo 1

2. None:
If you set the Stretch property to None, the content will preserve its original size.
<Viewbox Stretch="Fill" MaxWidth="100" MaxHeight="100" Name="viewBox1">

<Image Source="images/microsoft_silverlight.jpg"/>
</Viewbox> <Viewbox Stretch="Fill" MaxWidth="200" MaxHeight="200" Name="viewBox2">
<Image Source="images/microsoft_silverlight.jpg"/>
</Viewbox> <Viewbox Stretch="Fill" MaxWidth="300" MaxHeight="300" Name="viewBox3">
<Image Source="images/microsoft_silverlight.jpg"/>
</Viewbox>
//Set the Stretch property to None

private void stretchNone(object sender, RoutedEventArgs e)

{
viewBox1.Stretch = Stretch.None;
viewBox2.Stretch = Stretch.None;
viewBox3.Stretch = Stretch.None;
}
ViewBox Demo 2
Picture: ViewBox Demo 2

3. Uniform:
If you set the Stretch property to Uniform, the content will resize to fit the ViewBox. The ViewBox will take as much space as require to show the entire content and also preserves the aspect ratio.
<Viewbox Stretch="Fill" MaxWidth="100" MaxHeight="100" Name="viewBox1">

<Image Source="images/microsoft_silverlight.jpg"/>
</Viewbox> <Viewbox Stretch="Fill" MaxWidth="200" MaxHeight="200" Name="viewBox2">
<Image Source="images/microsoft_silverlight.jpg"/>
</Viewbox> <Viewbox Stretch="Fill" MaxWidth="300" MaxHeight="300" Name="viewBox3">
<Image Source="images/microsoft_silverlight.jpg"/>
</Viewbox>
//Set the Stretch property to Uniform

private void stretchNone(object sender, RoutedEventArgs e)

{
viewBox1.Stretch = Stretch.Uniform;
viewBox2.Stretch = Stretch.Uniform;
viewBox3.Stretch = Stretch.Uniform;
}
ViewBox Demo 3
Picture: ViewBox Demo 3

4. UniformToFill:
If you set the Stretch property to UniformToFill, the content will resize to fill the destination dimension. If the original size differs than the aspect ratio of the ViewBox, the content is then clipped to fit the ViewBox dimension.
<Viewbox Stretch="Fill" MaxWidth="100" MaxHeight="100" Name="viewBox1">

<Image Source="images/microsoft_silverlight.jpg"/>
</Viewbox> <Viewbox Stretch="Fill" MaxWidth="200" MaxHeight="200" Name="viewBox2">
<Image Source="images/microsoft_silverlight.jpg"/>
</Viewbox> <Viewbox Stretch="Fill" MaxWidth="300" MaxHeight="300" Name="viewBox3">
<Image Source="images/microsoft_silverlight.jpg"/>
</Viewbox>
//Set the Stretch property to UniformToFill

private void stretchNone(object sender, RoutedEventArgs e)

{
viewBox1.Stretch = Stretch.UniformToFill;
viewBox2.Stretch = Stretch.UniformToFill;
viewBox3.Stretch = Stretch.UniformToFill;
}
ViewBox Demo 4
Picture: ViewBox Demo 4

Overview

Silverlight 4 provides a large collection of UI controls for Silverlight application development. These controls are require to do the UI design of the application for giving a better representation to the user. You can customize the look & feel by creating your own Style or extending the control to give more power to the UI. I will describe the control styling in later chapters.
Here is some of the Silverlight 4 controls that I want to describe for you:
  1. TextBlock
  2. TextBox
  3. PasswordBox
  4. RichTextBox
  5. ComboBox
  6. ListBox
  7. CheckBox
  8. RadioButton
  9. Button

TextBlock

TextBlock is the primary element for displaying text inside your Silverlight Application. You will find it useful whenever you want to display some strings. TextBlock is a FrameworkElement available in the System.Windows.Controls namespace. There is a property named “Text” where you have to enter the text string.
<TextBlock Text="Hello Silverlight" />
This is not necessary for you to use the Text property to set some text inside your TextBlock control. TextBlock control can also be used as a container to set a para of strings. Hard enter to place a line break can be set using the <LineBreak/> control.
<TextBlock>
<TextBlock.Text>
This is the first line of Text.<LineBreak/>
This is the second line of Text.</TextBlock.Text>
</TextBlock>

OR

<TextBlock>
This is the first line of Text.<LineBreak/>
This is the second line of Text.
</TextBlock>

Also, you can represent a series of strings contained inside different Run elements instead of presenting as a single string. In that scenario, each Run element can have different font attributes set towards it. The LineBreak element will represent an explicit new line break
<TextBlock>
<LineBreak/>
<Run Foreground="Maroon"FontFamily="Arial"FontSize="30"
FontWeight="Bold">Arial Bold 30</Run>
<LineBreak/>
<Run Foreground="Teal"FontFamily="Times New Roman"FontSize="18"
FontStyle="Italic">Times New Roman Italic 18</Run>
<LineBreak/>
<Run Foreground="SteelBlue"FontFamily="Verdana"FontSize="14"
FontWeight="Bold">Verdana Bold 14</Run>
</TextBlock>

TextBlock
You will see various Properties and Events available for TextBlock control to do text formatting and other operation.

TextBlock Properties

TextBox

TextBox is another important element in Silverlight. It is also available inside the System.Windows.Controls. Unlike TextBlock, the TextBox inherits from the base class Control. Whenever you want to enter some text inputs from your user using your Silverlight application, you need the help of TextBox. It is one of the most important input control for Silverlight for data entry.
<TextBox Height="25" Width="200" Text="This is a Single Line TextBox"/>

<TextBox Height="100" Width="200"
HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Auto"
TextWrapping="Wrap"
Text="This is a Multi-Line TextBox. This is a Multi-Line TextBox."/>



public static readonly DependencyProperty AcceptsReturnProperty;
Set “AcceptsReturn” to True if you want to insert a Hard line break explicitly in your TextBox by your user. From code behind if you want to set the value to AcceptsReturnProperty of the TextBox, you have to call the SetValue() and then pass the DependencyProperty with the appropriate value:
myTextBox.SetValue(TextBox.AcceptsReturnProperty, true);
myTextBox.SetValue(TextBox.AcceptsReturnProperty, false);
From XAML, you can set it as:
<TextBox AcceptsReturn="True"/>

public static readonly DependencyProperty IsReadOnlyProperty;
Set “IsReadOnly” to True if you want your TextBox as only readable by your user. This is very useful when you are putting a Edit Button near your TextBox to give the user chose whether he wants to update some texts.
To set it from the code behind use the same format of the SetValue() method. Here’s the code:
myTextBox.SetValue(TextBox.IsReadOnlyProperty, true);

public static readonly DependencyProperty MaxLengthProperty; 
Set “MaxLength” to a positive numeric value , your user can’t add more than the specified value. Suppose you are setting it to 50, hence after inserting 50 characters the TextBox caret will not go forward.
You can set the Max Length property from code behind C# like this:
myTextBox.SetValue(TextBox.MaxLengthProperty, 150);
public static readonly DependencyProperty SelectionBackgroundProperty;
“SelectionBackground” color once set, your selected text will have the specified background. You can set both Solid Brush or Gradient Brush as your selection background. If you want to set it from code behind, use the following convention:
myTextBox.SetValue(TextBox.SelectionBackgroundProperty, new SolidColorBrush(Colors.Black));
public static readonly DependencyProperty SelectionForegroundProperty;
Like “SelectionBackground” the “SelectionForeground” will set the specified color as the foreground color of the selected text. The property SelectionForeground property can also be set in the same way. In this case, it will change the color of the font for the selected text. Have a look:
myTextBox.SetValue(TextBox.SelectionForegroundProperty, new SolidColorBrush(Colors.Black));

public static readonly DependencyProperty TextAlignmentProperty
 “TextAlignment” is responsible to set the text alignment to left, right, center or justify.
public static readonly DependencyPropertyTextProperty;
“Text” property contains the Text entered into the TextBox. You can set it in the same way from XAML & Code as I mentioned above.
public static readonly DependencyProperty TextWrappingProperty; 
Set “TextWrapping” to Wrap so that, if your entered text becomes longer than the specified width of the TextBox, it will populate the remaining text in a separate line (as described in the MultiLineTextBox figure).

PasswordBox

PasswordBox is available inside the System.Windows.Controls and inherits from Control. Whenever you need to add a Password field in your Silverlight application form to give the user access to login with credential, you have to use this password box. You will find it useful when you need to do login.
<PasswordBox Width="200" Height="25"Password="kunal2383" />
<PasswordBox Width="200" Height="25" Password="kunal2383"PasswordChar="X" />

Here are some useful DependencyProperty of the PasswordBox:
public static readonly DependencyProperty MaxLengthProperty;
Set “MaxLength” to a positive numeric value , your user can’t add more than the specified value. Suppose you are setting it to 50, hence after inserting 50 characters the TextBox caret will not go forward.
public static readonly Dependency PropertyPasswordCharProperty; 
Sets the password character of the control. The default value for password character of the field box is the asterisk (*). But you can change it by setting the value to this dependency property. If you set ‘X ‘ as password character, whatever you enter in the textbox of the field will display as ‘X’.
public static readonly DependencyPropertyPasswordProperty;
Gets or Sets the password property of the PasswordBox. If you set the text it will be visible in the UI in asterisk format.
public static readonly DependencyPropertySelectionBackgroundProperty; 
“SelectionBackground” color once set, your selected text will have the specified background.
public static readonly DependencyPropertySelectionForegroundProperty;
Like “SelectionBackground” the “SelectionForeground” will set the specified color as the foreground color of the selected text.

RichTextBox

Like TextBoxRichTextBox also inherits from Control and available in the namespace System.Windows.Controls. It is useful when you want to give a input box to your user where they can able to format the entered text like word processor. You can display text in various text format like Bold, Italic, Underline, Left/Right/Center align, various font size/color etc.
Have a look into the following XAML code where the RichTextBox has several <Paragraph> tag to split the text in various parts. You can use <Bold>,<Italic> tags to format the entered text. You can also align the text or change the font-size or font-color by setting the proper attributes to the <Paragraph> tag.
<RichTextBox Height="153"Width="336"AcceptsReturn="True">
<Paragraph>
This is a RichTextBox control having multiple paragraphs inside it.
You will find it more useful while creating an Editor control in Silvelight application.
<LineBreak />
</Paragraph>
<Paragraph>
<Bold>This Text is in Bold</Bold>
<LineBreak />
<Italic>This Text is in Italic</Italic>
</Paragraph>
<ParagraphTextAlignment="Right">
This Text is Right aligned.<LineBreak />
</Paragraph>
<ParagraphTextAlignment="Center">
<Hyperlink>This is an Hyperlink Button and center aligned</Hyperlink>
</Paragraph>
</RichTextBox>
Here is the output of the above XAML code:

You can see here that, not only formatted text you can also enter hyperlinks to the RichTextBox control. If you set the AcceptsReturn=”True” your user can explicitly enter hard line break by pressing the “Enter” key.

ComboBox

ComboBox is an items control which works like a ListBox but only one item is visible at a time. It inherits from Selector control and available in the System.Windows.Controls namespace. It contains ComboBoxItem which inherits from ListBoxItem. ComboBoxItem is also present in the same namespace as ComboBox is i.e. System.Windows.Controls namespace.
Let us create a simple ComboBox having some contents inside it. Set the Width of the ComboBox to a specific value, let’s say 200 in our case. Now add ComboBoxItem as the Items of the Combo. This step is not always require (in case of XAML atleast). Set some string as the “Content” of the ComboBoxItem. Here you may ask one question, is it only supports text? The answer is “No”. You can also set any FrameworkElement inside the Content of the ComboBoxItem, such as TextBlock, TextBox, Button, Rectangle etc.
Have a look into the XAML code here:
<ComboBox Width="200">
<ComboBox.Items>
<ComboBoxItem Content="Item 01"/>
<ComboBoxItem Content="Item 02"/>
<ComboBoxItem Content="Item 03"/>
<ComboBoxItem Content="Item 04"/>
<ComboBoxItem Content="Item 05"/>
<ComboBoxItem Content="Item 06"/>
<ComboBoxItem Content="Item 07"/>
<ComboBoxItem Content="Item 08"/>
<ComboBoxItem Content="Item 09"/>
<ComboBoxItem Content="Item 10"/>
</ComboBox.Items>
</ComboBox>
The output of the above XAML will initially look like the below figure:
Now once you click on the small arrow at the right side of the ComboBox, you will see a menu comes out from it containing the content you added there:

Here are some properties those you will find useful while working with the ComboBox:
IsDropDownOpen:
Once set to True the drop down will show with the content. By using this property you can programmatically control the visibility of the dropped menu. By default it is set to False and when you click on the small arrow it sets it to True and thus it opens up in the screen.
IsEditable:
From the name you can easily understand the functionality of this property. By default it is set as False. Hence, in the normal scenario you can’t type anything inside the ComboBox. If you want to edit the content of the ComboBox or want to type inside it, just set the value to True.
MaxDropDownHeight:
You can control the size of the drop down menu. If you set it to some numeric value, the height will be set as per the entered value.

ListBox

ListBox inherited from Selector present inside the System.Windows.Controls namespace. It contains ListBoxItem as Items. It represents it’s children as list. The followings are the DependencyProperties of ListBox:
public static readonly DependencyProperty IsSelectionActiveProperty;
public static readonly DependencyProperty ItemContainerStyleProperty;
public static readonly DependencyProperty SelectionModeProperty;
Some important properties are described below:
SelectionMode:
Gets or Sets the Selection Behaviour of ListBox control. There are three different modes of the Selection of the ListBoxItem: Single, where user can select only one ListBoxItem at a time; Multiple, where user can select multiple items without pressing a Modifier Key; Extended, where user can select multiple items by pressing a Modifier Key. The default mode is “Single”.
<ListBox Width="200"SelectionMode="Multiple" Height="200">
<ListBox.Items>
<ListBoxItem Content="Item 01"/>
<ListBoxItem Content="Item 02"/>
<ListBoxItem Content="Item 03"/>
<ListBoxItem Content="Item 04"/>
<ListBoxItem Content="Item 05"/>
<ListBoxItem Content="Item 06"/>
<ListBoxItem Content="Item 07"/>
<ListBoxItem Content="Item 08"/>
<ListBoxItem Content="Item 09"/>
<ListBoxItem Content="Item 10"/>
</ListBox.Items>
</ListBox>

The above example shows you how the ListBox looks like in different SelectionMode. The first example demonstrates “Multiple Selection Mode”. This type of listbox you need to give your user a choice to select multiple items. In the second example shows a simple “Single Selection Mode”, where the user can only select a single choice.

CheckBox

Checkbox inherits from ToggleButton and resides inside System.Windows.Controls namespace. Using this you can give your user a choice to select multiple items. There are three different states for CheckBox. If checked will return true, unchecked will return false and the third state returns null value. Generally the third state is not that much useful in normal scenarios. Use “Content” to set value (e.g. string, rectangle etc) to the checkbox.
Have a look into the following example:
<CheckBoxIsChecked="True"Content="Set as Checked (True)" />
<CheckBoxIsChecked="False"Content="Set as UnChecked (False)" />
<CheckBoxIsThreeState="True"IsChecked="{x:Null}"Content="Set as Third State (Null)" />
<CheckBoxIsEnabled="False"IsChecked="True"Content="Set as Checked, but disabled" />
<CheckBox>
<CheckBox.Content>
<Grid>
<EllipseHorizontalAlignment="Stretch" Fill="Red" />
<TextBlock Text="Multi Element as Checkbox Content" />
</Grid>
</CheckBox.Content>
</CheckBox>

The first code demonstrates the Checked item, the second code demonstrates unchecked item and third code demonstrates the third state. Third states becomes null. In the fourth code you will see the disabled state of the checkbox. What about the fifth code? Yup, in the fifth code we have added a Ellipse and a TextBlock wrapped with a Grid panel. It is not always necessary to set string as content. As per your requirement you can set anything. But be sure that CheckBox.Content only supports a single element and if you want to set multiple elements wrap with a panel as I demonstrated above.

RadioButton

Like CheckBox the element name RadioButton placed inside System.Windows.Controls assembly namespace also inherits from ToggleButton and contains the same properties as described above in CheckBox examples.
<RadioButtonIsChecked="True" Content="Set as Checked (True)" />
<RadioButtonIsChecked="False" Content="Set as UnChecked (False)" />
<RadioButton>
<RadioButton.Content>
<Grid>
<EllipseHorizontalAlignment="Stretch" Fill="Red" />
<TextBlock Text="Multi Element as RadioButton Content" />
</Grid>
</RadioButton.Content>
</RadioButton>
<RadioButtonGroupName="MyGroup" Content="Set under MyGroup"IsChecked="True" />
<RadioButtonGroupName="MyGroup" Content="Set under MyGroup" />


Normally if you are setting multiple radio buttons inside a page, you can select only one of them. If you need your user to select radio button from each different group of your option you can set a group name to the radio button. By grouping the options using a group name will allow your user to select a single radio option from each group.

Button

Button control in Silverlight inherits from ButtonBase class and can be found under the System.Windows.Controls namespace. Button controls are mainly require to Submit forms or for navigation panels. You can style it as per your need.
You can set some text as it’s content or can place any framework element inside it. If you want to add more than one element inside it, you have to use any panel wrapped to your elements.
See the below code on how we can use Button controls:
<StackPanel x:Name="LayoutRoot" Margin="20" Background="White">
<Button Content="I am a button control" Height="25" Width="200" Margin="5" />
<Button Height="25" Width="200" Margin="5">
<Button.Content>
<CheckBox Content="Checkbox inside Button" />
</Button.Content>
</Button>
<Button Width="200">
<Button.Content>
<StackPanel Orientation="Horizontal">
<Rectangle Width="30" Height="25" Fill="Green" Margin="0,0,5,0" />
<TextBlock Text="Rectangle inside Button" />
</StackPanel>
</Button.Content>
</Button>
</StackPanel>
The first example is a simple button control whereas the second contains checkbox as it’s content. The third example contains a Rectangle and a Text wrapped by Grid panel. This shows how we can use panel to load multiple elements inside a button.

Button has Click event where you can write your logic to do whatever you want once you click on the button e.g. navigation to a different view, submitting the form etc.