GVKun编程网logo

silverlight调用JS(silverlight插件怎么启用)

22

对于silverlight调用JS感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解silverlight插件怎么启用,并且为您提供关于Silverlight2学习教程(六):Silverli

对于silverlight调用JS感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解silverlight插件怎么启用,并且为您提供关于Silverlight 2学习教程(六): Silverlight托管代码调用Javascript中的JSON对象、Silverlight 5 beta新特性探索系列:1.安装Silverlight 5 beta环境以及OOB模式下Silverlight 5 多窗口支持、Silverlight HttpUtil 封装Post调用、SilverLight OOB模式与Com API交换的基础 和 C#编写Com 组件在SilverLight调用的宝贵知识。

本文目录一览:

silverlight调用JS(silverlight插件怎么启用)

silverlight调用JS(silverlight插件怎么启用)

Silverlight 2学习教程(六): Silverlight托管代码调用Javascript中的JSON对象

Silverlight 2学习教程(六): Silverlight托管代码调用Javascript中的JSON对象

 

在上一篇Blog文章中,讲述了JavaScriptSilverlight托管代码相互调用的一些方法。实际上,HtmlWindowGetProperty方法和Invoke/InvokeSelf方法的返回值是Object类型的,代表 DOM对象或者JavaScript对象(HtmlDocumentHtmlElementHtmlObjectScriptObject)的返回值自动作为最接近的类型进行返回,但是,程序开发人员仍然需要明确地将该对象转换成相应的类型。所有的数字,由于跨浏览器的原因,都作为Double类型返回,如果需要Int32类型,则执行Convert.ToInt32()方法即可。

在现代的Web应用中,JSON的使用越来越频繁。Silverlight 2中要调用JavaScript中的JSON对象,首先在托管代码中声明一个类,类的属性与JSON对象的属性一致(不必完全一致),然后在托管代码中将ScriptObject对象转换成声明的这个类型即可。

下面是一个完整的例子:

Page.xaml

<UserControl x:Class="SilverlightApplication1.Page"
    xmlns="http://schemas.microsoft.com/client/2007" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="600" Height="480">
    <Grid x:Name="LayoutRoot" Background="White">
        <Canvas Canvas.Top="20">
            <TextBlock Canvas.Top="10" Canvas.Left="20">请输入您的姓名: </TextBlock>
            <TextBox x:Name="UserInput" Width="200" Height="30" Canvas.Top="40" Canvas.Left="20"></TextBox>
            <TextBlock x:Name="Msg" Canvas.Top="90" Canvas.Left="20" Foreground="Navy" FontSize="18" Width="500"></TextBlock>
            <Button Click="Button_Click" Content="单击我" FontSize="24" Width="160" Height="60" x:Name="BtnTest" Canvas.Top="160" Canvas.Left="20"></Button>
            <Button Click="JSONButton_Click" Content="JavaScript JSON 对象测试" FontSize="24" Width="300" Height="50" Canvas.Top="240" Canvas.Left="20"></Button>
            <TextBlock x:Name="Msg2" Canvas.Top="300" Canvas.Left="20" Foreground="Navy" FontSize="18" Width="500"></TextBlock>
            <TextBlock x:Name="Msg3" Canvas.Top="320" Canvas.Left="20" Foreground="Navy" FontSize="18" Width="500"></TextBlock>
        </Canvas>
    </Grid>
</UserControl>

Page.xaml.cs

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;
using System.Windows.browser;
using System.Runtime.Serialization.Json;

namespace SilverlightApplication1
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }


        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string UserInputContent = this.UserInput.Text;
            if (UserInputContent.Equals(String.Empty))
            {
                UserInputContent = "Hello Silverlight World!";
            }
            else
            {
                UserInputContent = "你好," + UserInputContent;
            }
            HtmlWindow win = HtmlPage.Window;
            this.Msg.Text = UserInputContent;
            win.Alert("Silverlight 里面弹出的对话框。 " + UserInputContent);
            //执行页面中的js函数:
            win.Eval("getArraytest()");
            Object[] args = { "将此参数传递给 js 函数" };
            win.Invoke("getArrayTest", args);
         
            //如果页面中的值
            HtmlDocument doc = HtmlPage.Document;
            doc.GetElementById("UserName").SetAttribute("value", this.UserInput.Text);          
        }
        
        [ScriptableMember()]
        public string InterInvole()
        {
            string username = HtmlPage.Document.GetElementById("UserName").GetAttribute("value");
            this.UserInput.Text = username;
            this.Msg.Text = "您输入了:" + username; 
            return "你从js脚本中调用了 Silverlight 里面的方法。";
        }

        private void JSONButton_Click(object sender, RoutedEventArgs e)
        {
            ScriptObject so = HtmlPage.Window.Invoke("ReturnObject", nullas ScriptObject;
            Staple s = so.ConvertTo<Staple>();
            this.Msg2.Text = "大家好,我在  JavaScript JSON 对象中的名称是:" +  s.UserName;            
        }

        //接受Html页面传递的 JSON 字符串
        [ScriptableMember()]
        public void ReveiveJSON(string jsonString)
        {
            //注意引用:System.Runtime.Serialization.Json

            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Staple));
            System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.Unicode.GetBytes(jsonString));
            Staple staple = new Staple();
            staple = (Staple)json.Readobject(ms);
            Msg3.Text = "UserId = " + staple.UserId.ToString() + "  UserName = " + staple.UserName;
        }
    }

    public class Staple
    {
        public string UserName { setget; }
        public Double UserId { setget; }       
    }
}

App.xaml.cs

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;
using System.Windows.browser;

namespace SilverlightApplication1
{
    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)
        {
            // Load the main control           
            Page p = new Page();
            HtmlPage.RegisterScriptableObject("SilverlightApplicationExample", p);

            // 请注意这里的定义方法,如果这里的p写成 new Page(),则Javascript基本不能给 UserInput 赋值!
            this.RootVisual = p;
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {

        }
    }
}

SilverlightApplication1TestPage.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">
<head runat="server">
 <title>Silverlight 2托管代码与Javascript交互的例子</title>
 <script type="text/javascript">
 //<!{CDATA[
 //定义全局变量:
 var testvar = "孟宪会";
 
 //定义全局函数:
 function getArraytest()
 {
  if(arguments.length > 0)
  {
   alert("js 对话框:您传递了参数。" + arguments[0]);
   return  arguments[0];
  }
  else
  {
   alert("js 对话框:无参数调用。");
   return "js 函数返回值";
  }
 } 
 
function SetUserName()
{
  alert(SilverlightPlugin.Content.SilverlightApplicationExample.InterInvole());
}


 var Staple = {
               UserId:100,
               UserName:'孟宪会',
               SayHello:function(){alert(this.UserName)}
               };
               
function ReturnObject()
{
  return Staple;
}

function SendJSONToSilverlight()
{
  SilverlightPlugin.Content.SilverlightApplicationExample.ReveiveJSON(JSON.stringify(Staple));
}

//定义Silverlight插件对象
var SilverlightPlugin = null;;
function pluginLoaded(sender)
{
   SilverlightPlugin = sender.get_element();  
}
 //]]>
 </script>
 <script src="json2.js" type="text/javascript"></script>
 <!-- http://www.JSON.org/json2.js -->
</head>
<body style="height: 100%; margin: 0;">
 <form id="form1" runat="server">
 <div style="border: 2px solid #EEE; margin: 20px;padding:20px">
  请输入你的名字:<input id="UserName" type="text" value="" />
  <input type="button" onclick="SetUserName()" value="将名字传递到 Silverlight" /> <input type="button" onclick="SendJSONToSilverlight()" value="JSON传递到 Silverlight" /> 
 </div>
 <br />
 <div style="border: 2px solid #EEE;margin: 20px;">
  <asp:ScriptManager ID="ScriptManager1" runat="server">
  </asp:ScriptManager>
  <asp:Silverlight ID="Xaml1" runat="server" OnPluginLoaded="pluginLoaded" Source="~/ClientBin/SilverlightApplication1.xap" Version="2.0" Width="600px" Height="480px" />
 </div>
 </form>
</body>
</html>

单击“JavaScript JSON 对象测试按钮,运行结果如下:

Silverlight 5 beta新特性探索系列:1.安装Silverlight 5 beta环境以及OOB模式下Silverlight 5 多窗口支持

Silverlight 5 beta新特性探索系列:1.安装Silverlight 5 beta环境以及OOB模式下Silverlight 5 多窗口支持

        Silverlight 5 beta版本总算于昨日放出,怀着激动的心情今天将开发环境更新为Silverlight 5 beta版本,并且接触Silverlight 5 beta的第一个新特性:OOB模式下的多窗口的弹出显示。

        现在我们开始Silverlight 5 Beta版本的安装,首先需要为VS2010打一个VS2010 SP1补丁,然后我们再下载Silverlight 5 Beta Tools for Visual Studio SP1,一步一步安装完毕,最后我们下载Silverlight 5 Features Document 新特性的文档。至此我们即可踏上Silverlight 5开发的征程。

        对于Silverlight 5 beta版本下面的新窗口的支持是基于OOB模式下的,所以我们首先新建一个Silverlight 5的应用程序,然后右键项目属性-->"允许浏览器外运行应用程序"勾中-->点击"浏览器外设置"-->"在浏览器外运行时需要提升 的信任"勾上。如下图所示:

        然后我们在后台代码中键入以下代码即可弹出一个窗口,点击窗口中的按钮我们可以继续弹出窗口,实现了无限制的弹出窗口。当然所有弹出的子窗口都是依赖于父 窗口而存在的。(Tip:在Silverlight 4.0中的Window类修改的大小都是自身窗口的大小,并不能弹出窗口)

 

  
  
  1. public partial class MainPage : UserControl 
  2.   { 
  3.       public MainPage() 
  4.       { 
  5.           InitializeComponent(); 
  6.           PopWindow(400.0, 20.0, "第"+Flag+"个实例窗口"); 
  7.       } 
  8.       public static int Flag = 0; 
  9.       private void PopWindow(double left,double top,string title ) 
  10.       { 
  11.           //设置Window的通用属性 
  12.           Window testwindow = new Window(); 
  13.           testwindow.Height = 400; 
  14.           testwindow.Width = 500; 
  15.           testwindow.Top = top
  16.           testwindow.Left = left
  17.           testwindow.Title = title; 
  18.           testwindow.Visibility = Visibility.Visible; 
  19.  
  20.           //添加一个内部有按钮的Canvas,设置Canvas的背景色为白色 
  21.           Button btn=new Button(); 
  22.           btn.Width=80.0; 
  23.           btn.Height=30.0; 
  24.           btn.Content="点  击"
  25.           btn.Margin = new Thickness(5, top + Flag * 10, 0, 0); 
  26.           btn.Click += new RoutedEventHandler(btn_Click); 
  27.           Canvas canvas = new Canvas(); 
  28.           canvas.Children.Add(btn); 
  29.           canvas.Background = new SolidColorBrush(Colors.White); 
  30.           testwindow.Content = canvas; 
  31.  
  32.           //窗口默认值是WindowState.normal正常情况 
  33.           testwindow.WindowState = WindowState.normal; 
  34.               //WindowState.Maximized; 窗口最大化 
  35.               //WindowState.Minimized; 窗口最小化 
  36.               //WindowState.normal;    普通窗口 
  37.  
  38.       void btn_Click(object sender, RoutedEventArgs e) 
  39.       { 
  40.           PopWindow(400.0, "第"+Flag+"个实例窗口"); 
  41.       } 
  42.   } 

        本实例采用VS2010 +Silverlight 5 beta制作,如需源码请点击 SL5First.zip 下载。

Silverlight HttpUtil 封装Post调用

Silverlight HttpUtil 封装Post调用

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Threading;
using System.Text;


namespace Navi
{
    /*
     * 钟磊 20111127
     * 
     * 封装silverlight 中的Http Post调用
     *          
     * 使用时需要在应用的第一个构造函数中添加语句,否则无法取到Http响应头
     * 
     * bool registerResult = WebRequest.RegisterPrefix("http://",WebRequestCreator.ClientHttp);
     * 
     * 形如:
     * 
     * public MainPage()
       {
            //For Get Http Header
            bool registerResult = WebRequest.RegisterPrefix("http://",WebRequestCreator.ClientHttp);


            InitializeComponent();
     * }
     */


    public class HttpUtil
    {
        /*
         * * 
         * HTTP_CALLBACK 用户调用传入的回调函数
         * success 调用是否成功
         * compress 返回的stream是否是zip过的
         * flag 调用时传入的标记,用以在调用端区分是哪一个的回调
         * responseStream,Http响应传回的流
         */




        public delegate void HTTP_CALLBACK(bool success,bool compress,string flag,Stream responseStream);


        private byte[] _postData = null;
        private SynchronizationContext _syncContext = null;
        private HTTP_CALLBACK _cb = null;
        private string _flag;//当前调用的动作
    


        public HttpUtil(){}




        public void Post(string strPara,string strUrl,string strFlag,HTTP_CALLBACK cb)
        {
            //保存当前调用线程上下文(用户线程)
            _syncContext = SynchronizationContext.Current;
            _cb = cb;
            _postData = Encoding.UTF8.GetBytes(strPara);
            _flag = strFlag;


            Uri endpoint = new Uri(strUrl,UriKind.Absolute);
            HttpWebRequest request = WebRequest.Create(endpoint) as HttpWebRequest;
            request.Method = "POST";
            IAsyncResult asyncResult = request.BeginGetRequestStream(
                new AsyncCallback(callback_resuest),request);
        }


        private  void callback_resuest(IAsyncResult result)
        {
            HttpWebRequest request = result.AsyncState as HttpWebRequest;
            request.ContentType = "application/x-www-form-urlencoded";
            Stream requestStream = request.EndGetRequestStream(result);
            requestStream.Write(_postData,_postData.Length);
            requestStream.Close();
            request.BeginGetResponse(new AsyncCallback(callback_response),request);           
        }


        private void callback_response(IAsyncResult asyncResult)
        {          
            HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
            WebResponse response = request.EndGetResponse(asyncResult);


            //回调界面,返回用户线程
            _syncContext.Post(callback_ui,response);          
        }




        private void callback_ui(object state)
        {
            HttpWebResponse response = state as HttpWebResponse;                        


            //与服务端约定返回数据是否压缩(ZIP)标志
            bool compress = (response.Headers["COMPRESS"].toupper() == "TRUE");


            //与服务端约定的成功标志
            bool success = (response.Headers["RESULT_CODE"].toupper() == "OK");


            //回调
            _cb(success,compress,_flag,response.GetResponseStream());
                        
            response.GetResponseStream().Close();
            response.Close();                        
        }
    }

}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//这样调用

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

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.Text; using System.Threading; using System.IO; using Navi; using System.Net.browser; namespace Silverlight_HttpDemo {         public partial class MainPage : UserControl     {         private string para = @" sql=select * from sys_czyb where rownum < 3 &USER=app_user &CHARSET=UTF-8 &FUN=select &COMPRESS=true &SPLITE_ROW=| &SPLITE_COL=^ ";         private string url = "http://10.111.43.18:8099/pmias/servlet/db_proc_common";                  public MainPage()         {             //For Get Http Header             bool registerResult = WebRequest.RegisterPrefix("http://",WebRequestCreator.ClientHttp);             InitializeComponent();             para = para.Replace("\r\n","");         }                                //请求获取文本         private void button1_Click(object sender,RoutedEventArgs e)         {             new HttpUtil().Post(para,url,"GET_TXT",this.http_cb);                     }         //请求获取数据后保存         Stream savefile;         private void button2_Click(object sender,RoutedEventArgs e)         {             SaveFileDialog sf = new SaveFileDialog();                          if (sf.ShowDialog() == true)             {                 savefile = sf.OpenFile();                 new HttpUtil().Post(para,"SAVE_FILE",this.http_cb);             }         }         //回调函数         private void http_cb(Boolean success,Stream responseStream)         {             String fmt = @"成功:{0} 压缩:{1} 内容:{2}";             string content = "未定义";             switch (flag)             {                 case "SAVE_FILE":                     {                                                 if (success == false)                         {                                            //失败,不写入文件,取出错误信息                             if (compress)                                 content = ZipUtil.ZipStream2String(responseStream);                             else                                 content = ZipUtil.Stream2String(responseStream);                             savefile.Close();                                                     }                         else                         {                             //成功,将返回的流写入文件                             if (compress)                                 ZipUtil.ZipStream2File(savefile,responseStream);                             else                                 ZipUtil.Stream2File(savefile,responseStream);                             savefile.Close();                             content = "成功";                                                     }                         content = String.Format(fmt,success,content);                                              }                     break;                 case "GET_TXT":                     {                                                 if (compress)                             content = ZipUtil.ZipStream2String(responseStream);                         else                             content = ZipUtil.Stream2String(responseStream);                                                  content = String.Format(fmt,content);                                             }                                                          break;                 default:                     MessageBox.Show("错误的flag:"+flag);                     break;             }             MessageBox.Show(content,"提示",MessageBoxButton.OK);                      }     } }

SilverLight OOB模式与Com API交换的基础 和 C#编写Com 组件在SilverLight调用

SilverLight OOB模式与Com API交换的基础 和 C#编写Com 组件在SilverLight调用

 

原文:

1.SilverLight OOB模式与Com API交换的基础:http://www.silverlightchina.net/html/tips/2010/0722/1610.html  

 

文章中操作调用的是COM组件,如果调用外部程序的话:可以用以下的方式:

 

 


2. C#编写Com 组件在SilverLight调用:http://silverlightchina.net/html/tips/2010/0728/1652.html

今天的关于silverlight调用JSsilverlight插件怎么启用的分享已经结束,谢谢您的关注,如果想了解更多关于Silverlight 2学习教程(六): Silverlight托管代码调用Javascript中的JSON对象、Silverlight 5 beta新特性探索系列:1.安装Silverlight 5 beta环境以及OOB模式下Silverlight 5 多窗口支持、Silverlight HttpUtil 封装Post调用、SilverLight OOB模式与Com API交换的基础 和 C#编写Com 组件在SilverLight调用的相关知识,请在本站进行查询。

本文标签: