www.91084.com

GVKun编程网logo

Silverlight调用js关闭页面(js怎么调用窗口关闭提示语)

13

如果您想了解Silverlight调用js关闭页面的相关知识,那么本文是一篇不可错过的文章,我们将对js怎么调用窗口关闭提示语进行全面详尽的解释,并且为您提供关于Silverlight2学习教程(六)

如果您想了解Silverlight调用js关闭页面的相关知识,那么本文是一篇不可错过的文章,我们将对js怎么调用窗口关闭提示语进行全面详尽的解释,并且为您提供关于Silverlight 2学习教程(六): Silverlight托管代码调用Javascript中的JSON对象、Silverlight HttpUtil 封装Post调用、Silverlight Navigation-Silverlight页面间自定义导航、SilverLight OOB模式与Com API交换的基础 和 C#编写Com 组件在SilverLight调用的有价值的信息。

本文目录一览:

Silverlight调用js关闭页面(js怎么调用窗口关闭提示语)

Silverlight调用js关闭页面(js怎么调用窗口关闭提示语)

js: 

function exit() {
      window.opener = null;
      window.open('','_self');
      window.close();
}

 

Silverlight:

using System.Windows.browser;

HtmlPage.Window.Invoke("exit","Invoke");

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 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 Navigation-Silverlight页面间自定义导航

关于Silverlight  Navigation导航我一直想写一篇文章总结一下在项目中实际应用. Navigation导航是关联一个应用程序中实现功能多样化最基本需求. 导航也可以详细分为应用程序导航[应用中多为Page之间],外部导航,集成浏览器导航等. Silverlight 发展今天版本4 当然也在这个方面做出很多努力. 从1.1 2.0 NavigationService到今天出现Frame控件,导航框架等. 逐渐丰富加强这方面运用. 本篇的目的自定义一个导航帮助类 实现Silverlight 中页面间导航操作. 先看看效果[稍微有点大]:

在项目中使用 新建三个测试页面 分别命名为:NvgTestPageOne /Two/Three.xaml,默认初始页TestPageone.xaml,可以从TestPageone跳转Two 跳转后可以通过Back按钮返回上一页. 当然各个页面间也支持直接跳转,整个流程如图:

实现步骤: 自定义导航帮助类-NavigationHelper

A:引用空间

 
 
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using System.Reflection;  

B:在NavigationHelper声明变量:

 
 
  1. //声明  
  2. private static Grid FrameGrid = new Grid();//用存储导航页面和实现操作  
  3. private static Dictionary<string, string> getFrameDic = new Dictionary<string, string>();//记录整个跳转流程 

C:从当前页面跳转到一个新页面:

 
 
  1. /// <summary>  
  2.          /// 跳转新页面  
  3.          /// </summary>  
  4.          public static void NavigationFrame(UserControl sendpage)  
  5.          {  
  6.              App getcurentapp = Application.Current as App;  
  7.              if (getcurentapp != null)  
  8.              {  
  9.                //保存老页面  
  10.                  Grid rootgrid=getcurentapp.RootVisual as Grid;  
  11.                  UserControl getoldpageCon = rootgrid.Children[0] as UserControl;  
  12.                //测试发现问题:SendPage.Name有可能为空. 换利用Type的属性值   
  13.                  //添加时注意键不能重复  
  14.                  bool isreply = false;  
  15.                  foreach (keyvaluePair<string, string> getkey in NavigationHelper.NavigationHelp.getFrameDic)  
  16.                  {  
  17.                      if (getkey.Key.Equals(sendpage.GetType().Name + "old"))  
  18.                      {  
  19.                          isreply = true;//已经存在  
  20.                      }  
  21.                  }  
  22.    
  23.                  if (!isreply)  
  24.                  {  
  25.                      NavigationHelp.getFrameDic.Add(sendpage.GetType().Name + "old", getoldpageCon.GetType().Name);  
  26.                  }  
  27.    
  28.                  //跳转新页面  
  29.                  rootgrid.Children.Clear();  
  30.                  rootgrid.Children.Insert(0, sendpage);  
  31.                  getcurentapp.RootVisual = rootgrid;  
  32.              }  
  33.          } 

这个方法参数就是要跳转到页面UserControl. 通过操作App.RootVisual中Grid. 把新页面作为子控件添加到Grid.Children集合中. 当然跳转后如果Back返回操作. 我们必须记录这个跳转流程在Dictionary<stringstring>中. 页面间记录识别模式如下:

D:返回到上一页

 
 
  1. /// <summary>  
  2.          /// 自动跳转到上一页 类似IE的历史记录  
  3.          /// </summary>  
  4.          public static void NavigationBackFrame(UserControl CurrentPage)  
  5.          {  
  6.              bool isexit = false;//是否存在上一页 或是判断是否是根目录  
  7.              string backpage = string.Empty;  
  8.              foreach (keyvaluePair<string,string> getkey in NavigationHelp.getFrameDic)  
  9.              {  
  10.                  if (getkey.Key.Equals(CurrentPage.GetType().Name+"old"))  
  11.                  {  
  12.                      isexit = true;//存在  
  13.                      backpage =getkey.Value;  
  14.                      //MessageBox.Show(backpage); 测试成功  
  15.                  }  
  16.              }  
  17.    
  18.              if (!string.IsNullOrEmpty(backpage))  
  19.              {  
  20.                  //返回上一页  
  21.                  UserControl getbackControl = NavigationHelp.NavigationGetControlByName(backpage);  
  22.                  if (getbackControl != null)  
  23.                  {  
  24.                      App getcurentapp = Application.Current as App;  
  25.                      Grid rootgrid = getcurentapp.RootVisual as Grid;  
  26.    
  27.                      //跳转  
  28.                      rootgrid.Children.Clear();  
  29.                      rootgrid.Children.Insert(0, getbackControl);  
  30.                      getcurentapp.RootVisual = rootgrid;  
  31.                  }  
  32.              }  
  33.              else 
  34.              {  
  35.                  //不存在或是已经是根目录  
  36.                  MessageBox.Show("当前已经是根目录!");  
  37.              }  
  38.          } 

BackFram如上方法参数是当前页Control 传入后在Dictionary中查找对应跳转流程上一页记录. 然后跳转. 其中获取对应各页Control利用Assembly发射原理.具体方法实现如下:

F:获得一个具体页面Control:

 
 
  1. /// <summary>  
  2.          /// 通过Control的名称利用反射获取 UserContol实例对象./  
  3.          /// </summary>  
  4.          public static UserControl NavigationGetControlByName(string controlname)  
  5.          {  
  6.              //获取当前Assembly  
  7.              UserControl getpageControl = null;  
  8.              Assembly getcurrentass = Assembly.GetExecutingAssembly();  
  9.    
  10.              foreach (Type gettype in getcurrentass.GetTypes())  
  11.              {  
  12.                  if (gettype.Name.Equals(controlname))  
  13.                  {  
  14.                      //存在该Control  
  15.                      getpageControl = Activator.CreateInstance(gettype) as UserControl;      
  16.                  }  
  17.              }  
  18.              return getpageControl;  
  19.          } 

G:调用方式

如从Testpageone跳转到TestpageTwo页面 如下:

 
 
  1. //调用导航帮助类下公开当行方法 跳转到TestpagetTwo  
  2. UserControl sendpageCon=NavigationHelper.NavigationHelp.NavigationGetControlByName("NvgTestPageTwo");  
  3. NavigationHelper.NavigationHelp.NavigationFrame(sendpageCon);  

如果从TestPageTwo页面返回到TestpageOne 调用如下:

 
 
  1.  //调用导航帮助类 返回记录上一页  
  2. UserControl currentControl = NavigationHelper.NavigationHelp.NavigationGetControlByName("NvgTestPageTwo");  
  3. NavigationHelper.NavigationHelp.NavigationBackFrame(currentControl);  

直接跳转就更简单 同方式一类似.

如上一个简单方式实现Silverlight页面间跳转自定义帮助类. 简便快捷.当然如上只是简单跳转.实际运用中涉及到页面间参数的传递,值状态保留等问题. 完全可以在这个基础之上加以扩展即可.关于更多的Silverlight Navigation实现方式 稍后会有介绍.

关于Silverlight Navigation项目源代码下载见附件。

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调用js关闭页面js怎么调用窗口关闭提示语的分享就到这里,希望大家有所收获,若想了解更多关于Silverlight 2学习教程(六): Silverlight托管代码调用Javascript中的JSON对象、Silverlight HttpUtil 封装Post调用、Silverlight Navigation-Silverlight页面间自定义导航、SilverLight OOB模式与Com API交换的基础 和 C#编写Com 组件在SilverLight调用等相关知识,可以在本站进行查询。

本文标签: