在C#代码中获取Silverlight的初始化initparams参数

今天学习内容是,我们将利用Silverlight给我们提供的一个便利的方法来实现: 当一个web page加裁时,把指定参数(或信息)从 web page传递到silverlight中,这就是initParams。
  我们可以利用它把诸如页面url等相关信息传递到silverlight中(当然也可以传递其它信息)。
  initParams 信息是按照 string/value对的方式来存放的。我们将学习如何设置以及如何读取它们。下面开始我们的实验。
  仍按惯例,新建一个Silverlight应用程序,命名为:SLInitParamsFromWbToSL。如图:

一、在Web Page页面上放置我们将要传递的InitParams信息(InitParams信息设置格式与放置位置)。
WebPage页面是放置我们Silverlight控件的Host页面(本例为SLInitParamsFromWbToSLTestPage.aspx页面内容),其代码是:

<%@ 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>SLInitParamsFromWbToSL</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/SLInitParamsFromWbToSL.xap" MinimumVersion="2.0.31005.0" Width="100%" Height="100%"  InitParameters="Australia=Mebourne,China=ChengDu,USA=Washington"/>
</div>
</form>
</body>
</html>

其间我们可以看到有一个Siverlight控件<asp:Silverlight ID="Xaml1" />,我们的InitParams信息将放置在其中,因为它有一个InitParams参数,设置格式为:

InitParameters="Australia=Mebourne,China=ChengDu,USA=Washington"

这就是将要传递到Silverlight中的InitParams 键值对信息.
二、在Silverlight中读取我们传递过来的InitParams信息。
   当上面的页面(SLInitParamsFromWbToSLTestPage.aspx)加裁时,InitParameters的信息将会传递到Silverlight应用程序中,也即:传递到Silverlight的 App中,那么,我们如何在Silverlight application中获取InitParameters的信息呢?
    我们知道,当我们新建一个Silverlight application时, Visual Studio 会为我们自动创建四个文件: App.xaml, App.xaml.cs, Page.xaml, and Page.xaml.cs. 通常,我们只关注后面两个文件,但当我们想要获取initParams时,我们就必须要关注App.xaml与App.xaml.cs文件了。
    App.xaml.cs文件的内容如下:

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 Page();
        }
private void Application_Exit(object sender, EventArgs e)
        {
        }
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {   }
private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {}
}

     在此文件中,我们要特别关注Application_Startup 方法,它是在当Silverlight应用程序Startup事件触发时开始执行。其StartupEventArgs传入参数中含有一个名为InitParams的属性,其所含信息就是我们在第一步骤时设置的信息。而且,目前我们只有这么一个途径来取得InitParams中的信息。
下面我们有两个途径来实现在Page.xaml.cs后台代码中访问到此处的InitParams信息。
(一)途径一:通过在App.xaml.cs中添加一个属性来实现InitParameters信息的可访问性。。
       1、添加属性: MyInitParams ,代码如下:

public System.Collections.Generic.IDictionary  <string,string > MyInitParams { get;set;}

       2、在Application_Startup 方法中给属性MyInitParams 赋值

private void Application_Startup(object sender, StartupEventArgs e)
        {
this.RootVisual = new Page();
//在这个位置,我们可以找到 e.InitParams,它就是这个Silverlight程序的初始化参数
this.MyInitParams = e.InitParams; //在此处给我们上面建立的MyInitParams属性赋值
        }

        经过上面两步修改后的App.xaml.cs代码如下:

Code
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;
using System.Collections;
namespace SLInitParamsFromWbToSL
{
public partial class App : Application
    {
public System.Collections.Generic.IDictionary  <string,string > MyInitParams { get;set;}
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 Page();
//在这个位置,我们可以找到 e.InitParams,它就是这个Silverlight程序的初始化参数
this.MyInitParams = e.InitParams;
        }
private void Application_Exit(object sender, EventArgs e)
        {
        }
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
// 如果应用程序是在调试器外运行的,则使用浏览器的
// 异常机制报告该异常。在 IE 上,将在状态栏中用一个 
// 黄色警报图标来显示该异常,而 Firefox 则会显示一个脚本错误。
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 2 Application " + errorMsg + "\");");
            }
catch (Exception)
            {
            }
        }
    }
}

  3、在Page.xaml.cs中访问MyInitParams信息。
   i、按给定的Key访问Value

this.txtBxKey.Text = "澳大利亚的城市有: " + myApp.MyInitParams["Australia"];

  ii、遍历InitParams的内容

foreach (string key in myApp.MyInitParams.Keys)
            {
this.txtBxValue.Text += key + ": " + myApp.MyInitParams[key] + "\n";
            }

      Page.xaml.cs代码如下:

Code
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 SLInitParamsFromWbToSL
{
public partial class Page : UserControl
    {
public Page()
        {
            InitializeComponent();
            Loaded +=new RoutedEventHandler(Page_Loaded);
        }
private void Page_Loaded(object sender, EventArgs e)
        {
            App myApp = Application.Current as App;
//按Key值来访问对应的Value值
this.txtBxKey.Text = "澳大利亚的城市有: " + myApp.MyInitParams["Australia"];
//遍历InitParams的内容
foreach (string key in myApp.MyInitParams.Keys)
            {
this.txtBxValue.Text += key + ": " + myApp.MyInitParams[key] + "\n";
            }
        }
    }
}

(二)途径二:通过改造Page.xaml.cs的Page()构造函数来实现InitParameters信息的可访问性。
  1、在App.xaml.cs代码的Application_Startup方法中修改代码如下(把e.InitParams做为参数传递到Page构造函数中):

this.RootVisual = new Page(e.InitParams);

  2、修改Page.xaml.cs中的Page()构造函数,使其带有一个传入参数

public Page(IDictionary<string, string> initParams)
        {
            InitializeComponent();
        }

Page.xaml.cs全部代码如下:

Code
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 SLInitParamsFromWbToSL
{
public partial class Page : UserControl
    {
public Page(IDictionary<string, string> initParams)
        {
            InitializeComponent();
this.txtBxKey.Text = "澳大利亚的城市有: " + initParams["Australia"];
//遍历InitParams的内容
foreach (string key in initParams.Keys)
            {
this.txtBxValue.Text += key + ": " + initParams[key] + "\n";
            }
        }
    }
}

程序执行的效果如图:

原文地址:https://www.cnblogs.com/slteam/p/1605335.html