65.9K
CodeProject 正在变化。 阅读更多。
Home

Silverlight 应用程序开发入门

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.86/5 (30投票s)

2010年3月2日

CPOL

9分钟阅读

viewsIcon

96655

downloadIcon

1446

如何使用提供的不同开发选项来启动基本的 Silverlight 应用程序开发。

概述

当您想学习一项新技术时,选择正确的切入点非常重要。在本文中,我试图为 Silverlight 应用程序开发提供正确的起点。您将学习如何使用提供的不同开发选项来启动基本的 Silverlight 应用程序开发。我使用记事本启动了我的第一个 Silverlight 应用程序,这是 Silverlight 应用程序开发的现有正确切入点。然后,您将了解当您开始使用 Visual Studio 创建 Silverlight 应用程序时幕后发生的情况。您还将看到如何使用 Visual Studio 开发 Silverlight 应用程序,以及 Silverlight 应用程序模板创建的默认文件的详细列表。最后,您将了解 Silverlight 应用程序的生命周期。

使用记事本创建 Silverlight 应用程序

如果您是 Silverlight 新手,并想了解如何开始 Silverlight 应用程序开发,我鼓励您使用记事本(而不是 Visual Studio 或 Expression Blend)开发您的第一个 Silverlight 应用程序,这样您将完全理解 Visual Studio 2008 或 2010 在使用 Visual Studio 2008 项目模板创建 Silverlight 应用程序时幕后所做的工作。您可能会想,如何在不使用任何 Microsoft 开发工具的情况下使用记事本开始开发。是的,这是可能的;但是,您可能不会使用记事本编写实际的 Silverlight 应用程序。

如果您已准备好开始您的第一个 Silverlight 应用程序,请启动记事本并输入以下代码片段,然后将其保存为带有 .html 扩展名的文件。您可能想为您的应用程序起一个有意义的名称;在这里,我将其命名为 SilverlightApplicationInNotePad.html

<html>
  <head>
    <title>This is my first Silverlight Application developed using Notepad</title>
  </head>
     <script type="text/javascript" >
         // Create the MouseLeftButtonDownClick event handler for the root Canvas object.
         function MouseLeftButtonDownClick(sender, args) {
         
             var x = args.GetPosition(sender).x;
             var y = args.GetPosition(sender).y;
             
             // Retrieve a reference to the plug-in
             var plugin = sender.getHost();
             
             //Creates XAML content dynamically.
             var textblockXaml = '<TextBlock Canvas.Left=" ' + x + '" Canvas.Top="' + y + 
             '" FontSize="18" Text="hello" Foreground="#CCCCCC"/>'

             var textblock = plugin.content.CreateFromXaml(textblockXaml);
             // Add the XAML fragment as a child of the root Canvas object.
             sender.children.add(textblock);
         }
     </script>
 <script type="text/xaml" id ="xamlsource">
        <Canvas xmlns ="http://schemas.microsoft.com/client/2007"
          Width="640"
          Height="480"
          Background="Black"
          MouseLeftButtonDown="MouseLeftButtonDownClick">
            <TextBlock Canvas.Left="4" FontSize="18" 
               Text="My First Silverlight Application" Foreground="#CCCCCC"/>
            <Ellipse Canvas.Left="20"  Canvas.Top="50" 
            Fill="Orange" Width="200" Height="80" />
            <Rectangle Canvas.Left="250"  Canvas.Top="50" 
               Width="80" Height="80" Fill="Red"/>
            <Line Canvas.Left="20"  Canvas.Top="100" 
            X1="20" Y1="20" X2="100" Y2="100" Stroke="Yellow" StrokeThickness="10"/>
            <Polygon Canvas.Left="80"  Canvas.Top="140" 
            Fill="blue" Stroke="Green" StrokeThickness="10"
            Points="20,20 100,100 200,10"/>

            <Path Canvas.Left="160"  Canvas.Top="140" 
            Stroke="yellow" StrokeThickness="10">
                <Path.Data>
                    <PathGeometry>
                        <PathFigure StartPoint="20,20">
                            <BezierSegment Point1="120,0" 
                                Point2="50,300" Point3="200,200"/>
                        </PathFigure>
                    </PathGeometry>
                </Path.Data>
            </Path>
        </Canvas>
    </script>
  <body>
    <object type="application/x-silverlight" 
        id="silverlightControl"
        width="100%" 
        height="100%">
      <param name="background" value="Yellow"/>
      <param name="source" value="#xamlsource"/>
    </object>
  </body>
</html>

输出

输出非常令人兴奋,不是吗?Silverlight 致力于提供丰富的互联网应用程序(RIA),支持色彩鲜艳的动画媒体。现在,让我们一步一步地讨论 .html 文件中包含的内容。我们将进行一次演练,以帮助您理解创建用户界面 (UI) 所使用的内容,以及用于业务逻辑 (BL) 的内容,以及如何托管 Silverlight 应用程序。

步骤 1:使用 HTML 托管 Silverlight 应用程序

有多种技术可用于托管 Silverlight 应用程序,例如 HTML、ASP.NET、PHP 等。在此应用程序中,我们将讨论如何使用 HTML 托管 Silverlight 应用程序。

要使用 HTML 托管 Silverlight 应用程序,我们需要使用 Object 元素,该元素允许您在 HTML 中嵌入和配置 Silverlight 插件。这将帮助您的浏览器为 Silverlight 应用程序实例化该插件。

插件中有两个重要的配置属性

  • Type:您可以使用 type 属性指定 Silverlight 版本号。在这里,我没有指定任何版本,因此它将使用您 PC 上安装的可用版本。
  • Param:要指定 XAML 代码引用,需要使用参数标记。在此代码中,我使用了带 ID 的 #(井号),这样它会在同一文件中查找 XAML 源 ID。
<object type="application/x-silverlight" 
        id="silverlightControl"
        width="100%" 
        height="100%">
      <param name="background" value="Yellow"/>
      <param name="source" value="#xamlsource"/>
</object>

步骤 2:使用 XAML 代码创建用户界面

XAML 代表可扩展应用程序标记语言。它是一种基于 XML 的简单语言,用于使用分层关系创建和初始化 .NET 对象。虽然它最初是为 WPF 发明的,但现在我们也使用 XAML 来创建 Silverlight UI;在这里,为了简单起见,我将所有内容都放在同一个 HTML 文件中。但是,您将有一个单独的文件用于 XAML 代码,并通过 object 元素将 XAML 文件引用到您的 HTML 文件中。

上面 object 元素中 name = Source<Param> 元素用于为 XAML 代码指定一个名为“xamlsource”的 ID。Canvas 是一个容器标签,其中包含一些用于 UI 的 XAML 元素。我指定了一个名为“MouseLeftButtonDown”的事件;当用户在 Canvas 上单击鼠标左键时,它将调用 JavaScript 函数来显示一些内容。

<script type="text/xaml" id ="xamlsource">
    <Canvas xmlns ="http://schemas.microsoft.com/client/2007"
      Width="640"
      Height="480"
      Background="Black"
      MouseLeftButtonDown="MouseLeftButtonDownClick">
        <TextBlock Canvas.Left="4" FontSize="18" 
           Text="My First Silverlight Application" Foreground="#CCCCCC"/>
        <Ellipse Canvas.Left="20"  Canvas.Top="50" 
          Fill="Orange" Width="200" Height="80" />
        <Rectangle Canvas.Left="250"  Canvas.Top="50" 
          Width="80" Height="80" Fill="Red"/>
        <Line Canvas.Left="20"  Canvas.Top="100" 
          X1="20" Y1="20" X2="100" Y2="100" 
          Stroke="Yellow" StrokeThickness="10"/>
        <Polygon Canvas.Left="80"  Canvas.Top="140" 
          Fill="blue" Stroke="Green" StrokeThickness="10"
          Points="20,20 100,100 200,10"/>

        <Path Canvas.Left="160"  Canvas.Top="140" 
                 Stroke="yellow" StrokeThickness="10">
            <Path.Data>
                <PathGeometry>
                    <PathFigure StartPoint="20,20">
                        <BezierSegment Point1="120,0" 
                              Point2="50,300" Point3="200,200"/>
                    </PathFigure>
                </PathGeometry>
            </Path.Data>
        </Path>
    </Canvas>
</script>

步骤 3:使用 JavaScript 编写业务逻辑

同样,您不会将 JavaScript 代码保存在同一个文件中;相反,您可以有一个 .js 文件并在 .html 文件中引用它。这种浏览器支持的解释型非托管语言用于编写业务逻辑。在实际应用程序开发中,您将使用 C# 或 VB.NET 等托管编程语言编写代码。

当用户单击鼠标左键时,JavaScript 代码会读取 Canvas 表面的 X、Y 位置,并动态生成 XAML 代码并将其渲染到该位置。

GetHost 方法检索包含该对象的 Silverlight 插件实例。此方法在输入事件处理函数中检索 Silverlight 插件时特别有用,在该函数中,发送者参数通常是 DependencyObject

使用 CreateFromXaml 方法动态创建 XAML 内容,并将这些元素添加到 Canvas 的父元素,使用 sender.children.add 方法。

<script type="text/javascript" >
 // Create the MouseLeftButtonDownClick
 // event handler for the root Canvas object.
 function MouseLeftButtonDownClick(sender, args) {
 
     var x = args.GetPosition(sender).x;
     var y = args.GetPosition(sender).y;
     
     // Retrieve a reference to the plug-in
     var plugin = sender.getHost();
     
     //Creates XAML content dynamically.
     var textblockXaml = '<TextBlock Canvas.Left=" ' + x + 
       '" Canvas.Top="' + y + 
       '" FontSize="18" Text="hello" Foreground="#CCCCCC"/>'

     var textblock = plugin.content.CreateFromXaml(textblockXaml);
     // Add the XAML fragment as a child of the root Canvas object.
     sender.children.add(textblock);
 }
</script>

使用 Visual Studio 创建 Silverlight 应用程序

我假设在开始使用 Visual Studio 进行 Silverlight 应用程序开发之前,您的计算机上已经准备好了一个 Silverlight 应用程序开发环境。如果不是,请访问我的另一篇文章 Silverlight 简介,了解有关开发工具的信息。

本节将逐步介绍使用 Visual Studio 2008 创建一个非常简单的 Silverlight 应用程序的过程。

步骤 1:在 Visual Studio 文件菜单中,选择“新建项目”对话框,然后选择“Silverlight 应用程序”模板。您可以选择 VB.NET 或 C# 作为编码的编程语言,并为您的解决方案起一个有意义的名称。

步骤 2:这是可选的;您可以在创建 Silverlight 应用程序本身时选择托管应用程序模板,或者如果您已经有一个托管此 Silverlight 项目的网站,则可以取消选中复选框并单击“确定”继续。

步骤 3:在我们开始实际开发之前,了解 Silverlight 和托管项目的解决方案资源管理器非常重要。Visual Studio 模板会在后台为开发人员做很多事情;然而,开发人员有责任了解幕后发生的事情。在这里,我们将讨论 Visual Studio 为我们创建的每一个文件。

Silverlight 应用程序项目文件

Silverlight 应用程序项目包含以下配置、程序集引用和代码文件

AppManifest.xml

这是生成应用程序包(.XAP 文件)所需的应用程序清单文件。您不得编辑此文件。当我们生成 Silverlight 应用程序时,此文件将自动更新。此文件标识了打包的程序集和应用程序入口点等…

<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Deployment.Parts>
    </Deployment.Parts>
</Deployment>

AssemblyInfo.cs 或 AssemblyInfo.vb

这个文件没什么新内容;如果您是 .NET 开发人员,您会在每个 .NET 应用程序中看到这个文件,它包含嵌入到生成的程序集中的名称和版本元数据。

Silverlight 项目引用

  • mscorlib.dll
  • System.dll
  • System.Core.dll
  • System.Net.dll
  • System.Windows.dll
  • System.Windows.Browser.dll
  • System.Xml.dll

App.xaml 和 App.xaml.cs 文件

这与 ASP.NET 应用程序的 Global.asax 文件非常相似。您可以为此文件命名,但它应该继承自 Application 类。这是您的 Silverlight 应用程序的入口点。

Silverlight 应用程序需要 App 类来显示应用程序用户界面。App 类通过使用 App.xamlApp.xaml.csApp.xaml.vb 来实现。当应用程序包(.xap 文件)创建后,Silverlight 插件会实例化 App 类。

App.xaml

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             x:Class="SilverlightApplicationWithVS.App">
    <Application.Resources>
    </Application.Resources>
</Application>

此文件提供以下服务

  • 应用程序入口点
  • 应用程序生命周期
  • 应用程序管理
  • 应用程序范围的资源
  • 未处理的异常检测
//App.xaml.cs
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 SilverlightApplicationWithVS
{
    public partial class App : Application
    {

        public App()        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

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

        }
        private void Application_UnhandledException(object sender, 
                     ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger
            // then report the exception using
            // the browser's exception mechanism.
            // On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application
                // to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling
                // should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(
                           delegate { ReportErrorToDOM(e); });
            }
        }
        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + 
                                  e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval(
                  "throw new Error(\"Unhandled Error in Silverlight Application " + 
                  errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}

MainPage 文件

这是应用程序的“开始”页面,您可以从中导航到应用程序的不同页面。您将使用 XAML 创建所有这些用户界面 (UI) 页面。此类应继承自 UserControl 类。

<!--MainPage.xaml-->
<UserControl x:Class="SilverlightApplicationWithVS.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:DesignWidth="640" d:DesignHeight="480">
    <Canvas xmlns ="http://schemas.microsoft.com/client/2007"
          Width="640"
          Height="480"
          Background="Black"
            MouseLeftButtonDown="Canvas_MouseLeftButtonDown" 
           >
        <TextBlock Canvas.Left="4" FontSize="18" 
            Text="My First Silverlight Application" Foreground="#CCCCCC"/>
        <Ellipse Canvas.Left="20"  Canvas.Top="50" 
            Fill="Orange" Width="200" Height="80" />
        <Rectangle Canvas.Left="250"  Canvas.Top="50"  
            Width="80" Height="80" Fill="Red"/>
        <Line Canvas.Left="20"  Canvas.Top="100" 
            X1="20" Y1="20" X2="100" Y2="100" Stroke="Yellow" StrokeThickness="10"/>
        <Polygon Canvas.Left="80"  Canvas.Top="140" 
            Fill="blue" Stroke="Green" StrokeThickness="10"
            Points="20,20 100,100 200,10"/>

        <Path Canvas.Left="160"  Canvas.Top="140" 
            Stroke="yellow" StrokeThickness="10">
            <Path.Data>
                <PathGeometry>
                    <PathFigure StartPoint="20,20">
                        <BezierSegment Point1="120,0" 
                             Point2="50,300" Point3="200,200"/>
                    </PathFigure>
                </PathGeometry>
            </Path.Data>
        </Path>
    </Canvas>
</UserControl>

您还可以有一个代码隐藏文件,用于使用 C# 或 VB.NET 编写事件处理逻辑。

//MainPage.xaml.cs
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 SilverlightApplicationWithVS
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Canvas_MouseLeftButtonDown(object sender, 
                     MouseButtonEventArgs args)
        {
            MessageBox.Show("Hello");
        }
    }
}

.xap 文件

每个托管应用程序都应该有一个名为“ClientBin”的文件夹,用于存放构建 Silverlight 应用程序项目时创建的 XAP 文件。这也被称为 Silverlight 应用程序包。应用程序包是一个压缩的 zip 文件,扩展名为 .xap,其中包含启动应用程序所需的所有文件。

托管 API 使您能够将托管程序集和资源文件打包到应用程序包(.XAP)文件中。Silverlight 插件负责加载应用程序包并提取其内容。

要验证压缩的 zip 文件,请将 XAP 文件(如 SilverlightApplicationWithVS.xap)重命名为 SilverlightApplicationWithVS.xap.zip。然后,您可以打开存档并查看内部文件。

XAP 文件系统有两个明显的好处

  • 它压缩您的内容:由于内容在到达客户端之前不会解压缩,因此可以减少下载应用程序所需的时间。如果您应用程序包含可以轻松压缩的大型静态资源,如 XML 文档或文本块,这一点尤为重要。
  • 它简化了部署:当您准备好将 Silverlight 应用程序上线时,只需将 XAP 文件复制到 Web 服务器,以及包含 Silverlight 内容区域的 SilverlightApplicationWithVSTestPage.html 或类似的 HTML 文件。您无需担心跟踪程序集和资源。

Silverlight.js

Silverlight.js 文件提供了 JavaScript 帮助函数,用于将 Silverlight 插件嵌入网页和自定义 Silverlight 安装体验。

您可以使用 createObjectcreateObjectEx 函数动态地将 Silverlight 插件嵌入网页。这些函数根据指定的参数生成 HTML object 元素。

Silverlight.js 文件随 Silverlight SDK 安装在以下位置:%ProgramFiles%\Microsoft SDKs\Silverlight\v2.0\Tools

SilverlightApplicationWithVSTestPage.aspx 测试页面

创建了两个文件来托管应用程序

步骤 4:生成解决方案。生成解决方案后,您将在“ClientBin”文件夹中找到一个 XAP 文件,它将显示以下输出

Silverlight 应用程序生命周期

Silverlight 应用程序生命周期实际上是从用户请求使用 Silverlight 技术开发的页面开始的。当 Web 用户发出请求时,Silverlight 插件会加载,该用户会下载包括清单在内的所有引用文件(XAP),这有助于创建应用程序类的实例,从而为用户渲染 Silverlight 页面。

结论

希望您喜欢我的文章;请写下您对本文的评论,这对我非常重要。

© . All rights reserved.