近來總是有朋友在詢問Xap和Html或者asp.net之間怎麼傳遞參數,下面我們來學習哈這個參數傳遞的過程。
首先建一個項目HtmlTSilverlight,在MainPage上放一個TextBlock來顯示Html或者Aspx檔案傳遞過來的參數;
接下來,在web項目的HtmlTSilverlightTestPage.aspx或者HtmlTSilverlightTestPage.html中添加需要使用的參數,一般這個地方傳遞伺服器路徑的較多,我們在此就傳遞一個伺服器路徑顯示在MainPage上放一個TextBlock上。
Xaml:
<Grid x:Name="LayoutRoot" Background="White"> <TextBlock Height="47" HorizontalAlignment="Left" Margin="52,49,0,0" x:Name="textBlock1" VerticalAlignment="Top" Width="311" /> </Grid>
.cs
public MainPage() { InitializeComponent(); this.textBlock1.Text = App.ServerUrl; }
再其次,我們修改Web項目中的HtmlTSilverlightTestPage.html檔案,添加傳遞參數。HtmlTSilverlightTestPage.aspx用法相同就再多解釋。
<body> <form id="form1" runat="server" style="height:100%"> <div id="silverlightControlHost"> <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%"> <param name="source" value="ClientBin/HtmlTSilverlight.xap"/> <param name="onError" value="onSilverlightError" /> <param name="background" value="white" /> <param name="minRuntimeVersion" value="4.0.50826.0" /> <param name="autoUpgrade" value="true" /> <param name="InitParams" value="ServerUrl=http://127.0.0.1/Service.aspx" /> <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none"> <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="擷取 Microsoft Silverlight" style="border-style:none"/> </a> </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div> </form></body>
我們添加了一個ServerUrl=http://127.0.0.1/Service.aspx的參數,接下來就是在MainPage裡面取到這個參數。
我們在APP.xaml.cs檔案裡添加一個靜態屬性,供其他的類訪問,在Application_Startup事件的參數StartupEventArgs中取出這個參數,代碼如下:
/// <summary> /// Html或者Aspx傳遞過來的伺服器路徑 /// </summary> public static string ServerUrl { get; set; } private void Application_Startup(object sender, StartupEventArgs e) { //取得參數 需要異常處理----如果取不到的時候 ServerUrl = e.InitParams["ServerUrl"].ToString(); this.RootVisual = new MainPage(); }最後,設定web項目為啟動項目,HtmlTSilverlightTestPage.html為起始頁,F5就看到如下效果,參數被我們取出顯示在了TextBlock上了。這個參數可以添加多個,請同學們自己嘗試。執行個體代碼下載:http://files.cnblogs.com/Clivia/HtmlTSilverlight.rar