Walkthrough: Integrating XAML into an ASP.NET Web Site Using Managed Code

This walkthrough describes how to use the ASP.NET server controls for Silverlight to display a Silverlight 2 application in an ASP.NET AJAX Web page. In addition, this walkthrough describes how to provide client-side interactivity by using the Silverlight managed-code APIs. You will create a Silverlight application that has a linked Web site application, incorporate a XAML file and media files, and incorporate code that defines mouse events, plays sounds and displays animation.

Extensible Application Markup Language (XAML) simplifies creating a UI for the .NET Framework programming model. You can create visible UI elements in the declarative XAML markup, and then control these UI elements programmatically.

See a run-time code example of this feature: Run.
See a video that shows this feature: Watch.

Prerequisites

In order to complete this walkthrough, you will need:

  • Microsoft Visual Studio 2008.
  • The .NET Framework version 3.5.
  • Silverlight version 2.
  • Silverlight Tools for Visual Studio 2008. For more information, see the download page on the Microsoft Download Center.
  • Graphics files that are used as part of the example. You can get the graphics in a compressed (.zip) file from the Microsoft Download Center.

Creating a Silverlight Application

To start, you will create a Silverlight application in Visual Studio 2008. When you create the Silverlight application, you can also create a Web site to host the Silverlight application.

To create a new Silverlight application in Visual Studio

  1. In the File menu, click New Project.

The New Project dialog box appears.

  1. In the Project types box, select the language that you want to use.
  2. Select Silverlight to show the available Silverlight templates. Under Visual Studio installed templates, select Silverlight Application.
  3. In the Name box, enter MyPianoV2.
  4. Specify the location to save the project and then click OK.

The Add Silverlight Application dialog box appears.

  1. Click OK to create the Silverlight application and a Web site that will host the Silverlight application.

When you create the Silverlight application, Visual Studio creates the following projects in the solution:

  • A Silverlight application named MyPianoV2.
  • A Web site named MyPianoV2.Web.

The two projects are linked by a Silverlight link. Each time that you build the Silverlight project, a compiled MyPianoV2.xap file is generated and added or updated under the ClientBin folder of the linked Web site. Additionally, Visual Studio adds a file that is named MyPianoV2TestPage.aspx to the Web site project that you will use to test the Silverlight application.

Adding XAML and Image Content

By default, the Silverlight Application includes a XAML file name Page.xaml. You will modify this file by adding specific XAML content to the Page.xaml file. This file will be incorporated into the MyPianoV2.xap file and displayed by the Silverlight control in the browser. The XAML content references specific images. The following procedure describes how to add XAML content and images to the Silverlight application.

To add XAML and image content to the Silverlight application

  1. Open the Page.xaml file.
  2. Replace the existing XAML with the following XAML:

XAML 

<UserControl x:Class="MyPianoV2.Page"

    xmlns="https://schemas.microsoft.com/client/2007"

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

    Width="400" Height="300">

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

        <Canvas x:Name="keys" RenderTransformOrigin="0,0">

            <Image Source="Images/bg.jpg" Height="500" Width="1024"/>

            <Image x:Name="imgC" Height="500" Width="1024" Canvas.Top="0" Source="Images/C.jpg" Opacity="0"/>

            <Image x:Name="imgC2" Height="500" Width="1024" Canvas.Top="0" Source="Images/C2.jpg" Opacity="0"/>

            <Image x:Name="imgD" Height="500" Width="1024" Canvas.Top="0" Source="Images/D.jpg" Opacity="0"/>

            <Image x:Name="imgD2" Height="500" Width="1024" Canvas.Top="0" Source="Images/D2.jpg" Opacity="0"/>

            <Image x:Name="imgE" Height="500" Width="1024" Canvas.Top="0" Source="Images/E.jpg" Opacity="0"/>

            <Image x:Name="imgF" Height="500" Width="1024" Canvas.Top="0" Source="Images/F.jpg" Opacity="0"/>

            <Image x:Name="imgF2" Height="500" Width="1024" Canvas.Top="0" Source="Images/F2.jpg" Opacity="0"/>

            <Image x:Name="imgG" Height="500" Width="1024" Canvas.Top="0" Source="Images/G.jpg" Opacity="0"/>

            <Image x:Name="imgG2" Height="500" Width="1024" Canvas.Top="0" Source="Images/G2.jpg" Opacity="0"/>

            <Image x:Name="imgA" Height="500" Width="1024" Canvas.Top="0" Source="Images/A.jpg" Opacity="0"/>

            <Image x:Name="imgA2" Height="500" Width="1024" Canvas.Top="0" Source="Images/A2.jpg" Opacity="0"/>

            <Image x:Name="imgB" Height="500" Width="1024" Canvas.Top="0" Source="Images/B.jpg" Opacity="0"/>

            <Path x:Name="CPath" Opacity="0.01" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Width="161.666656494141" Height="272.333312988281" Canvas.Left="135.5" Canvas.Top="138.83332824707" Data="M272.66667,140 L136,330 147.33333,336 162.66667,410.66667 247.33333,410 234.66667,330.66667 278,248 254,242.66667 258.66667,200.66667 296.66667,139.33333 272.66667,140" />

            <Path x:Name="C2Path" Opacity="0.01" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Width="91" Height="136.333319306374" Canvas.Left="263.5" Canvas.Top="105.500005066396" Data="M325.33333,106.66667 L264,202.66667 266,241.33333 307.33333,238.66667 354,138 351.33333,106.66666 326.66667,106" />

            <Path x:Name="DPath" Opacity="0.01" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Width="131" Height="274.333297729492" Canvas.Left="247.499999999999" Canvas.Top="137.499984741212" Data="M358,142.66667 L311.33333,243.33333 288.66667,246 248,330.66667 258,338 266.66667,411.33333 354,410.66665 347.33333,330.66668 374,246.66668 350,243.33336 352.66667,202.66669 378,138.00005 360.66667,140.00005" />

            <Path x:Name="D2Path" Opacity="0.01" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Width="70.3333129882813" Height="134.333319425583" Canvas.Left="356.83334350586" Canvas.Top="107.500003457069" Data="M394.66667,108.66667 L357.33333,204 359.33333,241.33333 398,240.66667 426.66667,134.66667 425.33333,108"/>

            <Path x:Name="EPath" Opacity="0.01" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Width="117.666656494141" Height="274.333343505859" Canvas.Left="358.833343505859" Canvas.Top="137.5" Data="M431.33333,140 L403.33333,245.33333 381.33333,248 359.33333,330 368.66667,339.33333 372,411.33333 458,411.33333 455.33333,331.33333 476,138 433.33333,138.66667"/>

            <Path x:Name="FPath" Opacity="0.01" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Width="99.6666564941406" Height="273.666680037975" Canvas.Left="470.83334350586" Canvas.Top="138.833345949649" Data="M486.66667,140.66667 L471.33333,332 477.33333,334 476.66667,412 563.33333,411.33335 564,339.33334 570,328 560,246.66665 535.33333,243.33331 530,139.3333 486.66667,139.33329" />

            <Path x:Name="F2Path" Opacity="0.01" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Width="51" Height="133.666656494141" Canvas.Left="534.166687011719" Canvas.Top="108.16665649414" Data="M538.66667,109.33333 L534.66667,137.33333 542,241.33333 584,240.66666 584.66667,205.33334 568,108.66667 540.66667,108.66668" />

            <Path x:Name="GPath" Opacity="0.01" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Width="111" Height="274.333343505859" Canvas.Left="570.166687011719" Canvas.Top="137.5" Data="M570.66667,248 L582.66667,336 582,411.33333 669.33333,410.66667 672.66667,332.66667 680.66667,330 655.33333,245.33333 631.33333,244 601.33333,138 578.66667,138 594.66667,244.66667 571.33333,248" />

            <Path x:Name="G2Path" Opacity="0.01" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Width="76.3333129882813" Height="131.666656494141" Canvas.Left="603.5" Canvas.Top="110.166664123534" Data="M612,111.33333 L604,136.66667 636,238.66667 636.66667,241.33333 679.33333,241.33333 679.33333,206.66667 641.33333,111.33334 612.66667,110.66668" />

            <Path x:Name="APath" Opacity="0.01" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Width="138.333312988281" Height="274.333343505859" Canvas.Left="655.5" Canvas.Top="137.5" Data="M665.33333,246 L694.66667,336.66667 686,411.33333 774.66667,410 785.33333,335.33333 793.33333,328.66667 750.66667,246.66667 722,243.33333 673.33333,138 656,138.66667 688.66667,216.66667 685.33333,245.33333 666,246" />

            <Path x:Name="A2Path" Opacity="0.01" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Width="95" Height="131" Canvas.Left="676.166687011719" Canvas.Top="110.833320617675" Data="M682,111.33333 L676.66667,138.66667 730.66667,240.66667 768.66667,241.33333 770.66667,204.00001 713.33333,111.33334 683.33333,111.33335" />

            <Path x:Name="BPath" Opacity="0.01" Fill="#FFFFFFFF" Stretch="Fill" Stroke="#FF000000" Width="172.333312988281" Height="275.666687011719" Canvas.Left="733.5" Canvas.Top="136.833320051431" Data="M758,247.33333 L806,333.33333 790,412 878,412 894.66667,334 905.33333,327.33333 764.66667,138.66667 734,137.33333 776.66667,207.33334 778.66667,246.66668 758.66667,248" />

            <MediaElement x:Name="C" AutoPlay="false" Source="Media/C.wma"/>

            <MediaElement x:Name="C2" AutoPlay="false" Source="Media/C2.wma"/>

            <MediaElement x:Name="D" AutoPlay="false" Source="Media/D.wma"/>

            <MediaElement x:Name="D2" AutoPlay="false" Source="Media/D2.wma"/>

            <MediaElement x:Name="E" AutoPlay="false" Source="Media/E.wma"/>

            <MediaElement x:Name="F" AutoPlay="false" Source="Media/F.wma"/>

            <MediaElement x:Name="F2" AutoPlay="false" Source="Media/F2.wma"/>

            <MediaElement x:Name="G" AutoPlay="false" Source="Media/G.wma"/>

            <MediaElement x:Name="G2" AutoPlay="false" Source="Media/G2.wma"/>

            <MediaElement x:Name="A" AutoPlay="false" Source="Media/A.wma"/>

            <MediaElement x:Name="A2" AutoPlay="false" Source="Media/A2.wma"/>

            <MediaElement x:Name="B" AutoPlay="false" Source="Media/B.wma"/>

        </Canvas>

    </Grid>

</UserControl>

Note:

No images will be displayed until you add them to the project later in this walkthrough.

  1. In Solution Explorer, right-click the root of the Silverlight application project (MyPianoV2), click Add, and then click New Folder.
  2. Name the new folder Images.
  3. In Solution Explorer, right-click the root of the Silverlight application project and select Open Folder in Windows Explorer.
  4. Copy the graphics files from the Images folder in the compressed (.zip) file to the Images folder that you created in step 4. For information about the compressed file that contains the graphics files, see the Prerequisites section of this walkthrough.

Note:

The compressed (.zip) file contains an Images folder and a Media folder. The files in the Media folder will be used later in this walkthrough.

  1. In the toolbar of the Solution Explorer window, click the Show All Files button.

The Images folder displays the available graphics files.

  1. Select all the files in the Images folder.
  2. Right-click the selected files and then click Include In Project.
  3. In the File menu, click Save All.
  4. In Solution Explorer, right-click the myPianoV2TestPage.aspx file in the Web site project and then click Set As Start Page.

The Image elements of the XAML in the Page.xaml file correspond to keys of a piano. The Path elements will be used to associate mouse events with each piano key. The MediaElement elements will be used to play the appropriate media content.

Adding Media Content

The next step is to add the sound files that are referenced by the MediaElement element in the XAML.

To add media content

  1. In Solution Explorer, right-click the Silverlight application project (MyPianoV2), click Add, and then click New Folder.
  2. Name the new folder Media.
  3. In Solution Explorer, right-click the root of the Silverlight Application project and then click Open Folder in Windows Explorer.
  4. Copy the media files from the Media folder in the compressed (.zip) file to the Media folder that you created in step 2. For information about the compressed file that contains the media files, see the Prerequisites section of this walkthrough.
  5. In the toolbar of the Solution Explorer window, click the Show All Files button.

The Media folder displays the available media files.

  1. Select all the files in the Media folder.
  2. Right-click the selected files and then click Include In Project.
  3. If the Properties window is not already open, in the View menu, click Properties Window.
  4. Select the media files and then in the Properties window, set Build Action to Resource.

Marking the media files as resources enables these files to be included in the .xap file. The XAML you added earlier will be used to play the media files.

Adding Interactivity by Using Managed Code

In this section, you will add interactivity by adding mouse event handlers for the piano keys. Additionally, you will add code to play the notes.

To add interactivity by using managed code

  1. In the Silverlight application project (MyPianoV2), open the Page.xaml.cs or Page.xaml.vb file.
  2. Update the existing Page class code with the following code. Make sure that you select the file that matches the language that is used in your project.

C#  

using System;

using System.Collections.Generic;

using System.Linq;

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 MyPianoV2

{

    public partial class Page : UserControl

    {

        // Fields

        private string[] keyNames = new string[] { "CPath", "C2Path", "DPath", "D2Path", "EPath", "FPath", "F2Path",

       "GPath", "G2Path", "APath", "A2Path", "BPath" };

        private static Canvas keysCanvas;

        public Page()

        {

            InitializeComponent();

            keysCanvas = keys;

            for (int i = 0; i < this.keyNames.Length; i++)

            {

                Path path = (Path)keys.FindName(this.keyNames[i]);

                path.MouseLeftButtonDown += new MouseButtonEventHandler(this.noteDown);

                path.MouseLeftButtonUp += new MouseButtonEventHandler(this.noteUp);

            }

   }

        private void noteDown(object sender, MouseButtonEventArgs e)

        {

            ((UIElement)sender).CaptureMouse();

            string pathName = ((Path)sender).Name;

            string noteName = pathName.Substring(0, pathName.IndexOf("Path"));

            Image image = (Image)keysCanvas.FindName("img" + noteName);

            image.Opacity = 1;

            MediaElement mediaElement = (MediaElement)keysCanvas.FindName(noteName);

            mediaElement.Play();

        }

        private void noteUp(object sender, MouseButtonEventArgs e)

        {

            ((UIElement)sender).ReleaseMouseCapture();

            string pathName = ((Path)sender).Name;

            string noteName = pathName.Substring(0, pathName.IndexOf("Path"));

            Image image = (Image)keysCanvas.FindName("img" + noteName);

            image.Opacity = 0;

            MediaElement mediaElement = (MediaElement)keysCanvas.FindName(noteName);

            mediaElement.Stop();

        }

    }

}

Visual Basic 

Imports System

Imports System.Collections.Generic

Imports System.Linq

Imports System.Windows

Imports System.Windows.Controls

Imports System.Windows.Documents

Imports System.Windows.Input

Imports System.Windows.Media

Imports System.Windows.Media.Animation

Imports System.Windows.Shapes

Partial Public Class Page

    Inherits UserControl

    ' Fields

    Private keyNames() As String = {"CPath", "C2Path", "DPath", "D2Path", "EPath", "FPath", "F2Path", "GPath", "G2Path", "APath", "A2Path", "BPath"}

    Private Shared keysCanvas As Canvas

    Public Sub New()

        InitializeComponent()

        keysCanvas = keys

        Dim i As Integer

        For i = 0 To (Me.keyNames.Length) - 1

            Dim path As Path = DirectCast(keys.FindName(Me.keyNames(i)), Path)

            AddHandler path.MouseLeftButtonDown, AddressOf Me.noteDown

            AddHandler path.MouseLeftButtonUp, AddressOf Me.noteUp

        Next i

    End Sub

    Private Sub noteDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)

        CType(sender, UIElement).CaptureMouse()

        Dim pathName As String = CType(sender, Path).Name

        Dim noteName As String = pathName.Substring(0, pathName.IndexOf("Path"))

        Dim image As Image = CType(keysCanvas.FindName(("img" + noteName)), Image)

        image.Opacity = 1

        Dim mediaElement As MediaElement = CType(keysCanvas.FindName(noteName), MediaElement)

        mediaElement.Play()

    End Sub 'noteDown

    Private Sub noteUp(ByVal sender As Object, ByVal e As MouseButtonEventArgs)

        CType(sender, UIElement).ReleaseMouseCapture()

        Dim pathName As String = CType(sender, Path).Name

        Dim noteName As String = pathName.Substring(0, pathName.IndexOf("Path"))

        Dim image As Image = CType(keysCanvas.FindName(("img" + noteName)), Image)

        image.Opacity = 0

        Dim mediaElement As MediaElement = CType(keysCanvas.FindName(noteName), MediaElement)

        mediaElement.Stop()

    End Sub 'noteUp

End Class 'Page

  1. Save the file.
  2. Press CTRL+F5 to run the page.
  3. Click the piano keys in the browser to play the piano.

The noteDown handler of the Page class plays individual notes when you click them. The noteUp handler stops a note from playing when you release the mouse button.

Note:

In order for the piano keys to play, sound must be correctly configured on your computer.

There are two projects that are created in this walkthrough. The first project is the Silverlight Application project (MyPianoV2) containing XAML and managed code. The second project is the Web site project (MyPianoV2.Web) that is linked to the Silverlight Application project. The following code shows an .aspx page from the Web site project (MyPianoV2Web). This page shows how to include the Silverlight server control in the Web page. The Source attribute of the Silverlight server control references the .xap application package.

C#  

<%\@ 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" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="https://www.w3.org/1999/xhtml" style="height:100%;">

<head runat="server">

    <title>ASP.NET Controls for Silverlight - Silverlight 2.0 Example</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/MyPianoV2.xap" MinimumVersion="2.0.31005.0" Width="1024px" Height="500px" />

        </div>

    </form>

</body>

</html>

Visual Basic 

<%\@ Page Language="VB" AutoEventWireup="true" %>

<%\@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"

    TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="https://www.w3.org/1999/xhtml" style="height:100%;">

<head runat="server">

    <title>ASP.NET Controls for Silverlight - Silverlight 2.0 Example</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/MyPianoV2.xap" MinimumVersion="2.0.31005.0" Width="1024px" Height="500px" />

        </div>

    </form>

</body>

</html>

See Also

ASP.NET Controls for Silverlight

XAML Overview

 

We look forward to your comments and feedback.

-- Erik Reitan
ASP.NET User Education
This posting is provided "AS IS" with no warranties, and confers no rights.