What’s New in Silverlight 5? – XAML Changes

What’s New in Silverlight 5?

شاهد كورس كامل سيلفرلايت 5 مجانا هنا.

This content is based on Beta release, expect many changes in the final release.

Read What’s New in Silverlight 5 series here.

Download Sample Code

 

Introduction

In this article, we’ll have a brief discussion of the new XAML features of Silverlight 5.

 

Overview

Silverlight 5 has the following changes in the XAML stack:

  • Implicit Data Templates
  • Ancestor RelativeSource
  • Binding in Styles
  • Markup Extensions
  • XAML Debugging

Let’s see them in action one after one.

 

Model

Our demos in this section are based on a very simple model consists of just a collection of paper books and audio books. We have the following business model:

public class Book
{
  public string Title { get; set; }
  public string Author { get; set; }
  public decimal Price { get; set; }
}

public class PaperBook : Book
{
  public string Isbn { get; set; }
  public int Pages { get; set; }
}

public class AudioBook : Book
{
  public TimeSpan Duration { get; set; }
}

And here’s our collection:

public class BookData : List
{
  public List PaperBooks
  {
    get
    {
      return (from b in this where b is PaperBook
          select (PaperBook)b).ToList();
    }
  }

  public List AudioBooks
  {
    get
    {
      return (from b in this where b is AudioBook
          select (AudioBook)b).ToList();
    }
  }

  public BookData()
  {
    this.Add(new PaperBook()
    {
      Title = "The Sixth Man",
      Author = "David Baldacci",
      Isbn = "9780446573108",
      Pages = 432,
      Price = 14.28m,
    });

    ...

    this.Add(new AudioBook()
    {
      Title = "Water for Elephants",
      Author = "Sara Gruen",
      Duration = new TimeSpan(11, 29, 00),
      Price = 21.56m,
    });
  }
}

 

Implicit Data Templates

Silverlight 5 has got one of the great features of data templates in WPF, Implicit Data Templates. Instead of explicitly attaching the data template to every control, you can set a data type (through the DataType property) that the data template will apply to and then the data template will be applied automatically to any control that’s trying to display that data type.

Keep in mind that an implicit data template applies only to controls that…

  • Trying to display the data type specified
  • Have a templatable content (e.g. collection controls)
  • Defined in the scope of the template

So the implicit data template won’t apply to any other control doesn’t meet those requirements.

Implementation:

Let’s see implicit data templates in action. In the following scenario we have a list box that uses a data template to display some books and it gets populated through the code:

<ListBox x:Name="books">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel>
        <TextBlock Text="{Binding Title}" FontWeight="Bold" />
        <TextBlock Text="{Binding Author}" />
        <TextBlock Text="{Binding Price, StringFormat='C'}" />
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

We could refactor this code by making the data template implicit, and this can be done by moving the data template from the list box to application resources (for instance) and specifying the data type, and then the data template will be applied automatically to each templatable-content control trying to display the data type specified:

<Application.Resources>
  <DataTemplate DataType="loc:Book">
    <StackPanel>
      <TextBlock Text="{Binding Title}" FontWeight="Bold" />
      <TextBlock Text="{Binding Author}" />
      <TextBlock Text="{Binding Price, StringFormat='C'}" />
    </StackPanel>
  </DataTemplate>
</Application.Resources>

<ListBox x:Name="books" />

Clear and simple, right?

Now let’s do something more interesting to see the real power of implicit data templates. Instead of having a simple data template, we’ll have two templates for the two types of books, once for the paper books, and the other for the audio books:

<DataTemplate DataType="loc:PaperBook">
  <StackPanel>
    <TextBlock Text="{Binding Title}" FontWeight="Bold" />
    <TextBlock Text="{Binding Author}" />
    <TextBlock Text="{Binding Price, StringFormat='C'}" />
    <TextBlock Text="{Binding Isbn}" />
    <TextBlock Text="{Binding Pages}" />
  </StackPanel>
</DataTemplate>

<DataTemplate DataType="loc:AudioBook">
  <StackPanel>
    <TextBlock Text="{Binding Title}" FontWeight="Bold" />
    <TextBlock Text="{Binding Author}" />
    <TextBlock Text="{Binding Price, StringFormat='C'}" />
    <TextBlock Text="{Binding Duration}" />
  </StackPanel>
</DataTemplate>

As you see, each data template will be applied to a templatable-content control that tries to display the data type it specifies. In addition, both the data templates would be applied to a collection control that tries to display a collection of both PaperBook and AudioBook.

 

Ancestor RelativeSource

This is another feature of XAML that Silverlight 5 has got from WPF. It allows you to bind to a property in a parent control. This is especially useful in situation where you are in a data template and wish to bind to a property in a control outside the template higher in the render tree.

Implementation:

You use {Binding.RelativeSource} to specify the source in the tree.

  • Use the AncestorType property to specify the type of the parent control that you wish to bind to.
  • Use AncestorLevel to specify how far is the parent control of the type specified from the current control.

The following TextBlock controls all bind to the same Tag property found in the root StackPanel:

<StackPanel Tag="Hello, World">

  <TextBlock Text="{Binding Tag, 
    RelativeSource={RelativeSource AncestorType=StackPanel}}" />

  <TextBlock Text="{Binding Tag, 
    RelativeSource={RelativeSource AncestorType=StackPanel, AncestorLevel=1}}" />

  <StackPanel>

    <TextBlock Text="{Binding Tag, 
      RelativeSource={RelativeSource AncestorType=StackPanel, AncestorLevel=2}}" />

    <Grid>

      <TextBlock Text="{Binding Tag, 
        RelativeSource={RelativeSource AncestorType=StackPanel, AncestorLevel=2}}" />

    </Grid>

  </StackPanel>

</StackPanel>

And here’s a more complex example. In the following example we change the color of a control inside an item template based on whether the item is selected or not. For this to work we bind to the IsSelected property of the ListBoxItem control (that represents an item on the list box) and we use a type converter to return a color based on a Boolean value:

<ListBox x:Name="books">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel>
        <TextBlock Text="{Binding Title}" FontWeight="Bold"
          Foreground="{Binding IsSelected, Converter={StaticResource conv},  
          RelativeSource={RelativeSource AncestorType=ListBoxItem}}" />
        <TextBlock Text="{Binding Author}" />
        <TextBlock Text="{Binding Price, StringFormat='C'}" />
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

 

 

Style Binding

This is another feature of XAML that Silverlight 5 has got from WPF. It allows you to bind directly in style setters, and that would allow changing styles automatically at runtime by changing source objects.

Implementation:

In the following scenario, we have a class that contains brushes used in the application:

public class MyBrushes
{
  public SolidColorBrush MainBrush { get; set; }

  public MyBrushes()
  {
    MainBrush = new SolidColorBrush(Colors.Red);
  }
}

And we have a style that binds to that class and gets the main brush from there (as you can see, all binding features are available now in style setters):

<loc:MyBrushes x:Key="brushes" />

<Style TargetType="TextBlock">
  <Style.Setters>
    <Setter Property="FontSize" Value="20" />
    <Setter Property="FontWeight" Value="Bold" />
    <Setter Property="Foreground"
        Value="{Binding MainBrush, Source={StaticResource brushes}}" />
  </Style.Setters>
</Style>

Finally, we can change the style automatically at runtime by changing the source brush using code like this:

  MyBrushes brshes = Application.Current.Resources["brushes"] as MyBrushes;
  brshes.MainBrush.Color = Colors.Red;

 

Markup Extensions

Markup extensions allow you to execute code at XAML parsing time, they are like {Binding}, {StaticResource}, {RelativeSource}, etc. The new feature of XAML in Silverlight 5 is the ability to create custom markup extensions. They provide more concise syntax, and they are easier and simpler than attached properties.

Implementation:

An example of a very simple markup extension is an extension that sums two numbers and returns the result to the control (the following TextBlock would have the text ‘3’ at runtime):

<TextBlock Text="{my:SumExtension FirstNumber=1, SecondNumber=2}" />

So how to create such an extension? You can create markup extensions by implementing the generic IMarkupExtenstion interface (in System.Xaml namespace) that accepts a type parameter specifies the return type from the extension (must be a reference type.) After that, you provide extension parameters as properties, and you implement ProvideValue() to do the work and return the results to the XAML.

The following code defines our summation extension:

public class SumExtension : IMarkupExtension<object>
{
  public int FirstNumber { get; set; }
  public int SecondNumber { get; set; }

  public object ProvideValue(IServiceProvider serviceProvider)
  {
    return (FirstNumber + SecondNumber).ToString();
  }
}

And here’s a more complex example. In the books scenario, we have defined a markup extension that returns a collection of books based on the book type (paper/audio):

public class BookLocatorExtension : IMarkupExtension<object>
{
  public BookType Type { get; set; }

  public object ProvideValue(IServiceProvider serviceProvider)
  {
    if (Type == BookType.Paper)
      return BookData.PaperBooks;
    else
      return BookData.AudioBooks;
  }
}

public enum BookType { Paper, Audio }

And here’s how we can use the extension:

<ListBox ItemsSource="{loc:BookLocator Type=Paper}" />

<ComboBox ItemsSource="{loc:BookLocator Type=Audio}" />

 

XAML Debugging

The last new XAML feature introduced in Silverlight 5 is the ability to debug data bindings. It is very useful when watching for binding errors and it works by placing a breakpoint inside the binding in XAML and watching the Locals window and other Visual Studio windows for binding details.

Keep in mind that XAML debugging works only in Internet Explorer 9.

Implementation:

In our books scenario, we have the following data form:

<UserControl.Resources>
  <loc:BookData x:Key="data" />
</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="White">
  <Grid.ColumnDefinitions>
    <ColumnDefinition />
    <ColumnDefinition />
  </Grid.ColumnDefinitions>

  <ListBox x:Name="booksList" 
            DataContext="{StaticResource data}"
            ItemsSource="{Binding}" />

  <StackPanel Grid.Column="1"
            DataContext="{Binding SelectedItem, ElementName=booksList}">

    <TextBlock>Title</TextBlock>
    <TextBox Text="{Binding Title, Mode=TwoWay}" />

    <TextBlock>Author</TextBlock>
    <TextBox Text="{Binding Author, Mode=TwoWay}" />

    <TextBlock>Price</TextBlock>
    <TextBox Text="{Binding Price, StringFormat='C', Mode=TwoWay}" />
  </StackPanel>
</Grid>

Now, put a breakpoint inside the binding in the list box and run the application to see what happens.

When you run the application, Visual Studio stops on the breakpoint while it loads the list box with data. Looking at the Locals window we can see binding details:

Here we have the details encapsulated in a BindingState, and the current state is UpdatingTarget means that it’s a Pull operation where list box gets loaded with data.

We can see that we have 5 items in the list referred by FinalSource. In addition, we don’t have any errors or validation errors yet.

Now stop the application, and let’s try something else. Try inserting the breakpoint into the Price text box instead and run the application.

As you can see, Visual Studio stops on both Push and Pull operations. The Pull operation happens when the text box get loaded by the data, and the Push operation happens when the value in the text box changes and gets updated to the source.

Now try writing some invalid data in the price text box (e.g. some letters) and watch the Locals Window:

Now you watch out any error that might happen in binding.

The last thing to mention is that conditions and filters can be used in the breakpoints. As an example, you can use the following condition to tell Visual Studio to stop only on binding errors and not in every operation:

((System.Windows.Data.Debugging.BindingDebugState)BindingState).Error != null

 

Summary

We had a discussion of the XAML stack in Silverlight 5 and we have talked about the 4 new features:

  • Implicit Data Templates:
    Allows you to automatically apply data templates to controls based on the data type the control uses.
  • Ancestor RelativeSource:
    Allows you to bind to a property in a parent control.
  • Binding in Styles:
    Allows you to use binding directly in style setters.
  • Markup Extensions:
    Allows you to execute code at XAML parsing time by using custom markup extensions.
  • XAML Debugging:
    Allows you debug data bindings.

Now, check out other What’s New in Silverlight 5? articles.

What’s New in Silverlight 5?

Silverlight 5

شاهد كورس كامل سيلفرلايت 5 مجانا هنا.

This content is based on Beta release, expect many changes in the final release.

Check out other Silverlight 5 articles here.

If you are new to Silverlight, check out this article.

What’s New – XAML Changes
What’s New – Control and Text Changes
What’s New – Graphics Changes
What’s New – Media Improvements
What’s New – Elevated-Trust Changes
What’s New – Other Improvements

Download Sourcecode

 

Silverlight 5

The first thing to know about Silverlight 5 is that it’s currently in beta, means that it definitely has bugs, and it also not yet feature-complete; some features are going to be shipped later in the final version. In addition, being in beta means that no go-live license available, this is for internal use and testing only so do not install on user’s machine.

Worth mentioning that Silverlight 5 was first announced at PDC 2010 conference (October 2010) and the beta version was shipped later at MIX11 (April 2011,) and the final version will be released soon this year.

 

Goal

Goals of the version 5 include:

  • Improving performance
  • Getting closer to WPF
  • Enabling line-of-business scenarios
  • Better development experience

 

Improvements

Silverlight 5 has come with lots of improvements and changes, and those improvements can be divided into several areas:

 

Getting Started

To get started you need to have first Microsoft Visual Studio 2010 Service Pack 1 installed on you PC. After that, you can go to http://silverlight.net and download the beta SDK and tools for VS2010.

In addition, you can install Microsoft Expression Blend Preview for Silverlight 5 Beta if you like using it.

After you have VS2010 SP1 and Silverlight 5 SDK installed on your PC, you can continue reading and start making your cool stuff!

Now let’s start with XAML changes, but first let’s take a look at our model that’s going to be used through all the samples.

 

What’s next?

Start with…

Introduction to Microsoft Silverlight

هذا الموضوع متوفر أيضا باللغة العربية، ومتوفر شرح فيديو أيضا، انظر هنا.

Contents

Contents of this article:

  • Contents
  • Overview
  • What is Silverlight
    • Definition
    • Platform Support
    • Rich Interactive Application
    • RIA Stats
    • Why Silverlight
    • Silverlight vs. Flash
    • Silverlight vs. WPF
    • Rich vs. Reach
    • Showcase
    • Deep Zoom
  • Deep Inside
    • Silverlight and XAML
    • Deployment Process
    • Silverlight Architecture
  • Silverlight 5
  • Tooling
    • Microsoft Visual Studio 2010
    • Microsoft Expression Studio 4
  • What’s Next
  • Demo
  • Summary

 

Overview

In this article we’ll have a brief introduction to Microsoft Silverlight, see how it fits with other technologies today, and watch it in action. Get ready!

 

What is Silverlight

Definition

Silverlight is a Microsoft technology aimed to help developers create rich interactive Web applications with the best user interface features and functionalities. It’s available as a plugin for almost all famous browsers available today, and it’s used to deliver the next generation media and Web applications.

Figure 1 - Silverlight Logo

Figure 1 - Silverlight Logo

When we say rich applications we don’t mean those with amazing interfaces and lots of graphics. Indeed, we mean by “rich” those have lots of functionalities not available for standard Web applications. Common examples of rich applications are online document editors and image processors; both are very interactive and offer lots of functionalities that are usually not available for standard Web applications. And that actually what Silverlight is devoted for, its main goal is to allow for developing rich interactive applications for the Web.

Platform Support

Unlike many other Microsoft technologies, Silverlight applications can run everywhere. It’s said to be cross-platform, cross-browser, and cross-device. It can run on Windows, Linux, and even Mac, it can run on Internet Explorer, Mozilla Firefox, Google Chrome, and many others, and it also can run on PCs, mobile devices, and handhelds. Really it can run everywhere without any code changes!

One more interesting thing is that Silverlight Web applications can be hosted on any server. You can host your Silverlight application on a Windows, Linux, or Mac server without any additional code changes or configuration.

Rich Interactive Applications

We have been talking about rich interactive applications for a while; now let’s see what a rich interactive application really means.

A Rich Interactive/Internet Application (RIA) is a Web application that’s very interactive with the user and has lots of functionalities. It’s very similar to desktop applications comparing interactivity and features; however, it’s a Web application that runs on the browser not the desktop. So we can say that RIA applications have the best functionalities and user interface features of desktop applications and Web applications.

Figure 2 - RIA

Figure 2 - RIA

Today, there’re lots of technologies available for creating RIA applications. The most famous platforms are Adobe Flash, Microsoft Silverlight, and Sun Java. Worth mentioning that every platform of the above mentioned (that includes Silverlight of course) is available through a plugin for the browser, and therefore its runtime must be installed on user’s machine in order to be able to run the application.

RIA Stats

Now someone asks: Who wins the race? What’s the best RIA platform that one can spend his time and effort to learn?

First of all, let’s have a look at the following diagrams that represent penetration rates of Adobe Flash, Microsoft Silverlight, and Sun Java. The first diagram we have comes from http://riastats.com and it shows that Adobe Flash is installed on almost 96% of internet-connected machines. Microsoft Silverlight comes in the second place with about 74% of total internet-connected machines. And Sun Java comes third with about 73% of internet-connected machines.

Figure 3 - RIA Stats

Figure 3 - RIA Stats

StatOWL shows a bit different data with more details:

Figure 4 - Stats from StatOWL

Figure 4 - Stats from StatOWL

Looking at the above diagrams we can see that Microsoft Silverlight did a great job in a very short time (first release was on 2007.) However, we can’t depend much on this data since, as you know, Microsoft Silverlight is installed automatically on Windows machines via Windows Update.

Now, let’s have a look at Microsoft Silverlight features and see what makes it the best RIA platform yet.

Why Silverlight

Other than being delivered by Microsoft, some features of Silverlight are:

  • It’s FREE.
  • It runs on all popular browsers, platforms, and devices.
  • It can be run in browser and as a desktop application.
  • Easy to create excellent UIs that looks “WOW”.
  • Enables business application development.
  • Supports 2D/3D animations/graphics.
  • Natively supports CLR and .NET Framework.
  • Can be automated using JavaScript.
  • Supports a variety of media (audio/video) formats with streaming capabilities.
  • Supports a variety of rich controls including the DataGrid.
  • Supports a variety of enterprise technologies including WCF.

In addition, Silverlight is considered to be the main development framework for Windows Phone.

Figure 5 - Windows Phone

Figure 5 - Windows Phone

Silverlight vs. Flash

Silverlight and Flash are very similar, so which is better, Silverlight or Flash? Since I’m a Microsoft developer and since you are reading now in a .NET blog, and although I haven’t ever developed for Flash, I can say that Silverlight is the best RIA platform ever!!! However, we need to be more serious.

InfoWorld did a review and compared between Silverlight and Flash, and the results were so great, Silverlight passed Flash and scored 8.3 points, while Flash got 7.8 points only.

Figure 6 - Silverlight vs. Flash, InfoWorld

Figure 6 - Silverlight vs. Flash, InfoWorld

Silverlight vs. WPF

Windows Presentation Foundation (WPF) is a graphical subsystem utilizing DirectX for rendering UI in Windows-based application, developed by Microsoft and introduced as part of Microsoft .NET Framework 3.0 and Windows Vista. WPF is considered to be the replacement for WinForms (that considered now Feature-Complete,) while WinForms relies on the older GDI subsystem, WPF relies on DirectX.

On the other hand, Silverlight is actually a subset of WPF, and formerly Silverlight was codenamed WPF/E (WPF/Everywhere) because it’s considered to be the cross-platform version of WPF. And while WPF focuses on desktop development, Silverlight focuses on Web development.

Figure 7 - Silverlight vs. WPF

Figure 7 - Silverlight vs. WPF

Rich vs. Reach

The following diagram compares some of the available Web development technologies in terms of richness (i.e. UI functionalities) and reach (platform and browser support.)

Figure 8 - Rich vs. Reach

Figure 8 - Rich vs. Reach

From the above diagram we can see that WPF has the best UI features today. However, it’s devoted primarily for desktop development, and it can run only on Windows platforms.

On the other hand, ASP.NET can run everywhere, but unfortunately it doesn’t support the UI functionalities required for today’s Web.

And finally, Silverlight has the best of UI functionalities, and it also supports a wide range of platforms and browsers (its platform/browser support is expanded each release.)

Showcase

To get a solid understanding of what Silverlight can do, check out some of the Silverlight applications from around the world:

And one of the most impressive applications is SilveOs (http://silveos.com/); a mini-operating system for the Web.

And thousands of Silverlight applications are available here too:  http://www.silverlight.net/showcase.

Deep Zoom

And another great feature of Silverlight is the DeepZoom technology that was introduced by Microsoft as part of Silverlight. DeepZoom allows you to view very large high resolution images. It reduces the time of initial load by downloading only the region being viewed at the resolution it’s displayed at. Subsequent regions are downloaded as the user pans to (or zooms into) them.

Figure 9 - Deep Zoom, Microsoft Silverlight

Figure 9 - Deep Zoom, Microsoft Silverlight

 

Deep Inside

Silverlight and XAML

Like WPF, user interface in Silverlight is declared in a specific language called Extensible Markup Language (or XAML, pronounced ‘Zammel’.) XAML is an XML-based language created by Microsoft which is used to initialize structured values and objects. XAML elements are mapped directly to CLR objects (e.g. a <Button> element maps to a Button object.)

Figure 10 - XAML Logo

Figure 10 - XAML Logo

Former ASP.NET developers are somewhat familiar with the nature of XAML. You have a WYSIWYG XAML designer that you use to design the interface of your application. The code for this interface is available through a code-behind file, where you can write in your preferred .NET language.

The concept of two files for the same page (e.g. a XAML file for the interface and a CS file for the C# code) separates two main roles in application development, design and development. The designer can work in the XAML file, and the developer can work in the code file, and both files are linked together. This also leads to a loosely-coupled design that separates user interface code from the business logic.

Figure 11 - Designer vs. Developer

Figure 11 - Designer vs. Developer

Deployment Process

What steps you would follow to deploy your Silverlight application to your users? That’s what this section is devoted for.

When you build your Silverlight application, the XAML markup, as well as the code and all other resources, is compiled into .NET assemblies which are then compressed using ZIP and stored in a XAP (.xap) file.

Figure 12 - XAP Files

Figure 12 - XAP Files

The XAP file can then be hosted in a Web server and referenced by Web pages declaring the Silverlight plugin object. And when the user navigates to the page, the XAP file is downloaded to his PC and executed on the Web page by the Silverlight runtime.

Figure 13 - Silverlight Application Deployment Process

Figure 13 - Silverlight Application Deployment Process

So all you need is just to develop your application, get the XAP file, insert the plugin into a Web page, and then publish the page and the XAP file to the Web.

Silverlight Architecture

The following illustration shows the essential architecture and components of Microsoft Silverlight. It shows how the presentation (interface) core components fit together with other .NET and Silverlight components, and what services does the provider offer.

Figure 14 - Silverlight Architecture

Figure 14 - Silverlight Architecture

 

Silverlight 5

The current stable version of Silverlight is Silverlight 4. Back to PDC 2010 the 5th version of Silverlight was introduced, it’s still in Beta but it’s supposed to be released soon.

Figure 15 - Silverlight 5 Logo

Figure 15 - Silverlight 5 Logo

Here’s a brief overview of the forthcoming Silverlight 5 features:

  • Media:
    • Hardware Video Decode
    • Better Power Management
    • Remote Control Support
  • Text and Printing:
    • Better Text Rendering
    • Full OpenType Support
  • Graphics:
    • GPU Accelerated Graphics
    • 3D Graphics Support
  • XAML:
    • XAML Debugging
  • Application Development:
    • Windows Azure Support
    • P/Invoke
  • Testing and Performance:
    • Automated UI Testing
    • Faster Startup
    • Hardware Acceleration
    • 64-bit Support

More about Silverlight 5 can be found here: http://www.microsoft.com/silverlight/future.

 

Tooling

The most common tools for Silverlight are Microsoft Visual Studio 2010 and Microsoft Expression Studio 4.

Microsoft Visual Studio 2010

Best for developers, good for designers. Check it out here: http://www.microsoft.com/visualstudio/en-us.

Figure 16 - Microsoft Visual Studio 2010

Figure 16 - Microsoft Visual Studio 2010

Microsoft Expression Studio 4

Consists of a 5 tools:

  • Microsoft Expression Blend
    Visual user interface builder for Silverlight and WPF.
  • Microsoft Expression Web
    WYSIWYG website designer and editor.
  • Microsoft Expression Design
    Raster and vector graphics editor.
  • Microsoft Expression Media
    Digital asset and media manager.
  • Microsoft Expression Encoder
    Profession media (video/audio) encoder
Figure 17 - Microsoft Expression Studio 4

Figure 17 - Microsoft Expression Studio 4

 

What’s Next

To start with Silverlight, you have to install the following components:

 

Demo

In the following example, we’ll create the Hello World application in Silverlight. Follow those steps:

First, ensure that Silverlight SDK is installed on your PC, and launch Visual Studio 2010 and select New Project.

Figure 18 - Creating a New Silverlight Application

Figure 18 - Creating a New Silverlight Application

From the New Project dialog, select your desired language from the left and select Silverlight as project type. From the middle pane, select Silverlight Application to start.

Now another dialog appears asks you to specify whether to create another Web application to host the Silverlight application or not. As you know, Silverlight applications run inside a plugin defined in a Web page, and that dialog asks if to create a new Web Application project for you to host the Silverlight application or to create just a simple HTML page to host it. Leave the dialog with no changes and ensure that you have selected Silverlight 4 from the Silverlight Version combo box and click OK to proceed.

Figure 19 - New Silverlight Application Settings

Figure 19 - New Silverlight Application Settings

Now let’s have a look at what Visual Studio has created for us. Looking at the Solution Explorer we can see that Visual Studio has created two projects, one is the Silverlight project, and the other is a Web project that’s going to host this Silverlight application.

Figure 20 - Silverlight Project in Solution Explorer

Figure 20 - Silverlight Project in Solution Explorer

Looking at the Web project we can see that VS has included two test pages in that project, the first is an ASPX page and the second is a simple HTML page, both define the Silverlight plugin and both are ready to show you your Silverlight application when you browse to them. The difference is that ASPX pages can define ASP.NET elements and code, while the simple static HTML cannot.

Back to the Silverlight application, we can see that it define 4 files:

  1. App.xaml:
    Define application-wide interface elements.
  2. App.xaml.cs (C# code file, linked to App.xaml):
    Define the startup logic and any other application-wide code.
  3. MainPage.xaml:
    The main application page; contains the interface elements.
  4. MainPage.xaml.cs (C# code file, linked to MainPage.cs):
    The business logic and code for the main application page.

Then we have two pages, the first is App.xaml that defines the application-wide elements and code (inside App.xaml.cs,) and the second is MainPage.xaml that defines the main page of your application where you can define your interface elements and code them (inside MainPage.xaml.cs.)

Now let’s design our interface. Go to MainPage.xaml and inside the <Grid> element define a Button (you can also drag the button from the Toolbox to the designer to define it):

<Button Width="100" Height="25" Content="Say Hello" Click="Button_Click" />
Figure 21 - Button in the Page

Figure 21 - Button in the Page

From the previous line of code we can see that we have defined a Button control using a <Button> element, and we have also set the control’s characteristics and properties using the element attributes. And to have our button respond to user clicks, we have wired up the Click event into the function Button_Click() that we’re going to define it in the code file.

Now go to MainPage.xaml.cs and define the Click event handler for the button:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Hello, World!");
}
Figure 22 - The Code-Behind File

Figure 22 - The Code-Behind File

Now run the application and try it.

Figure 23 - Running Silverlight Application

Figure 23 - Running Silverlight Application

Before we leave this section, let’s have a look over the plugin required for Silverlight. Go to and of the test pages on the Web project and step down until you reach the <object> element that defines the plugin. Simply, the Silverlight application requires only the following HTML code to define its plugin:

<div id="silverlightControlHost">
  <object data="data:application/x-silverlight-2,"
    type="application/x-silverlight-2" width="100%" height="100%">
      <param name="source" value="ClientBin/SilverlightApplication1.xap"/>
      ...
  </object>
  <iframe id="_sl_historyFrame"
      style="visibility:hidden;height:0px;width:0px;border:0px"></iframe>
</div>

As you see, we have references the XAP file in the page by using the source parameter. When you build your application in Visual Studio, it will create a new folder besides the test page called ClientBin and put the XAP file inside it so you can reference it in the page.

Clear, aih?

 

Summary

  • Silverlight is a cross-platform application framework for writing and running rich Internet applications (RIA.)
  • Its runtime is available as a cross-browser, cross-platform, and cross-device plug-in.
  • It’s the main development framework for Windows Phone.
  • It’s a subset of WPF so it depends on XAML for UI design.
  • You define the interface using XAML, and write the code using your preferred .NET language.
  • The XAML markup, as well as the code, is compiled into .NET assemblies and compressed into a XAP file.
  • The XAP file is then referenced by a prepared Web page and then downloaded to client’s PC when he navigates to the page.
  • Version 4 is the current stable version of Silverlight.
  • Silverlight 5 is currently in beta and it will be released soon.
  • You use Visual Studio 2010 and Microsoft Expression Studio for developing and designing your Silverlight application.
  • Microsoft Expression Studio is preferred for you if you are a designer.