热门:网页模板.net视频教程JQueryMVCjsonExtJs源码示例三级联动JQuery菜单
您现在的位置:.Net中文社区>> Silverlight>>正文内容

Silverlight 中一些必须知道的技巧

发布时间:2010年05月15日点击数: 佚名

1,在Silverlight获取初始化参数
页面上XAML代码如下:

  1. <Grid x:Name="LayoutRoot" Background="White"  > 
  2.         <ListBox Margin="76,68,0,197" x:Name="listBox" HorizontalAlignment="Left" Width="226"/> 
  3.     </Grid> 

用了listBox控件,为了显示多个参数值
前台HTML代码如下:

  1. <object data="data:application/x-silverlight," id="XamlObject" type="application/x-silverlight-2" 
  2.          width="100%" height="100%"> 
  3.          <param name="source" value="ClientBin/SilverlightTest11.0.xap" /> 
  4.          <param name="onerror" value="onSilverlightError" /> 
  5.          <param name="background" value="white" /> 
  6.          <param name="minRuntimeVersion" value="3.0.40818.0" /> 
  7.          <param name="autoUpgrade" value="true" /> 
  8.          <param name="initparams" value="id=12343,name=silverlight学习" /> 
  9.          <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40818.0" style="text-decoration: none;"> 
  10.              <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="获取 Microsoft Silverlight" 
  11.                  style="border-style: none" /> 
  12.          </a> 
  13.      </object> 

注意:name=initParams 这个节点,后面的value 他就是sl中要获取的参数,value中的参数一般定义为value="key=value,key=value..."
C#获取初始化参数.在App.xaml的 初始化方法Application_Startup写上如下代码:

  1. private void Application_Startup(object sender, StartupEventArgs e) 
  2.         { 
  3.             MainPage main = new MainPage(); 
  4.             this.RootVisual = main; 
  5.  
  6.             foreach (string item in e.InitParams.Keys) 
  7.             { 
  8.                 main.listBox.Items.Add(new TextBlock() 
  9.                 { 
  10.                     Text = String.Format("网页参数:{0} = {1}", item, e.InitParams[item]) 
  11.                 }); 
  12.             } 
  13.             

OK, 效果图我就不演示啦,大家自己试试...

2,Silverlight获取URL传递参数

  1. 这个比较简单,主要用了HtmlPage.Document.QueryString[key],key就是参数的名字了 

3,silverlight 捕获一些常用的浏览器信息

  1. <pre class="brush:csharp;collapse:true;">            BrowserInformation brow = HtmlPage.BrowserInformation; 
  2.             this.txtBlock1.Text = string.Format("浏览器名称:{0}",brow.Name); 
  3.             txtBlock1_Copy.Text = string.Format("浏览器版本:{0}", brow.BrowserVersion); 
  4.             txtBlock1_Copy1.Text = string.Format("浏览器操作系统名称:{0}", brow.Platform); 
  5.             txtBlock1_Copy2.Text = string.Format("代理字符串:{0}",brow.UserAgent); 
  6. </pre> 

4,silverlight操作HTML元素
 XAML代码省略
C# 代码:

  1. private void Button_Click(object sender, RoutedEventArgs e) 
  2.      { 
  3.          HtmlElement img = HtmlPage.Document.GetElementById("img11"); 
  4.  
  5.          img.SetAttribute("width",txtwidth.Text); 
  6.          img.SetAttribute("height", txtheight.Text); 
  7.      } 

前台HTML代码:

  1. <div> <img id="img11" src="silverlight.jpg" /></div> 

通过sl代码 来动态改变前台img的尺寸

5,HTML元素操作Silverlight对象

 XAML代码如下: 

  1. <Ellipse x:Name="elipse" Fill="White" Stroke="Black" Height="138" Margin="136,0,302,88" VerticalAlignment="Bottom"/> 
  2.         <TextBlock x:Name="txtState"  Height="20" Margin="136,0,317,53" VerticalAlignment="Bottom" TextWrapping="Wrap"/> 

C# 代码:

  1. public HtmlAndSilverlightDemo() 
  2.         { 
  3.             // 为初始化变量所必需 
  4.             InitializeComponent(); 
  5.             HtmlElement select = HtmlPage.Document.GetElementById("sel1"); 
  6.  
  7.             select.AttachEvent("onchange"new EventHandler<HtmlEventArgs>(Select_onChange)); 
  8.         } 
  9.  
  10.         public void Select_onChange(object sender, HtmlEventArgs e)  
  11.         { 
  12.             HtmlElement select = sender as HtmlElement; 
  13.             string value = select.GetAttribute("value"); 
  14.             txtState.Text = value; 
  15.             switch (value) 
  16.             { 
  17.                 case "红色"
  18.                     this.elipse.Fill = new SolidColorBrush(Colors.Red); 
  19.                     break
  20.                 case "绿色"
  21.                     this.elipse.Fill = new SolidColorBrush(Colors.Green); 
  22.                     break
  23.                 case "蓝色"
  24.                     this.elipse.Fill = new SolidColorBrush(Colors.Blue); 
  25.                     break
  26.                 default
  27.                     break
  28.             } 
  29.         } 

HTML代码:

  1. <div> 请选择:<select id="sel1"> 
  2.                <option value="红色">红色</option> 
  3.                <option value="绿色">绿色</option> 
  4.                <option value="蓝色">蓝色</option> 
  5.            </select></div> 

主要思路是,是通过前台的一个下拉列表的更改, 来改变silverlight中椭圆的颜色. 大家可以根据这个思路开扩展.

6,使用HttpUtility类

 UrlEncode 和UrlDecode 还有HtmlEncode和HtmlDecode 都是大家在做 Asp.net时候常用到的编码类.  在silvelight中 他在HttpUtility类中可调用 具体的调用和在asp.net中一样,这里就不做具体介绍了.

7,使用Document.Cookies读写Cookie

 为了操作简单,我写了一个CookieHelp类    c#代码如下:

  1. #region Cookie操作 
  2.  
  3.        /// <summary> 
  4.        /// 添加cookie 
  5.        /// </summary> 
  6.        /// <param name="key"></param> 
  7.        /// <param name="value"></param> 
  8.        public static void SetCookie(string key, string value) 
  9.        { 
  10.            DateTime expire = DateTime.UtcNow + TimeSpan.FromDays(30); 
  11.            string cookie = string.Format("{0}={1};expires={2}", key, value, expire.ToString("R")); 
  12.            HtmlPage.Document.SetProperty("cookie", cookie); 
  13.        } 
  14.  
  15.        /// <summary> 
  16.        /// 获取cookie 
  17.        /// </summary> 
  18.        /// <param name="key"></param> 
  19.        /// <returns></returns> 
  20.        public static string GetCookie(string key) 
  21.        { 
  22.            key += '='
  23.            string[] cookies = HtmlPage.Document.Cookies.Split(';'); 
  24.            foreach (string cookie in cookies) 
  25.            { 
  26.                string cookieStr = cookie.Trim(); 
  27.                if (cookieStr.StartsWith(key,StringComparison.OrdinalIgnoreCase)) 
  28.                { 
  29.                    //分隔出key的值 
  30.                    string[] vals = cookieStr.Split('='); 
  31.                    if (vals.Length >=2) 
  32.                    { 
  33.                        return vals[1];//返回值 
  34.                    } 
  35.                    return string.Empty; 
  36.                } 
  37.            } 
  38.            //没有找到就返回空字符串 
  39.            return string.Empty; 
  40.        } 
  41.  
  42.        #endregion 

8,使用 HtmlPage.Window类 页面导航

  1. string url = "www.baidu.com"
  2.  Uri uri = new Uri(url,UriKind.RelativeOrAbsolute); 
  3.  HtmlPage.Window.Navigate(uri); 

消息提示:
  三种弹出窗口:

  1. HtmlPage.Window.Alert("alert"); 
  2. HtmlPage.Window.Confirm("你确定吗?"); 
  3. HtmlPage.Window.Prompt("请输入密码"); 

9,在silverlight中调用javascript
XAML代码:

  1. <Canvas Height="74" Margin="8,129,48,0" VerticalAlignment="Top"> 
  2.         <TextBlock Height="18" Width="159" Canvas.Left="8" Canvas.Top="8" Text="2,在Silverlight调用Javascript" TextWrapping="Wrap"/> 
  3.         <Button Height="28" Width="111" Canvas.Left="19" Canvas.Top="39" Content="Invoke" Click="Button_Click_2"/> 
  4.         <Button Height="28" Width="111" Canvas.Left="151" Canvas.Top="39" Content="InvokeSelf" Click="Button_Click_3"/> 
  5.     </Canvas> 

C#:

  1. private void Button_Click_2(object sender, RoutedEventArgs e) 
  2.       { 
  3.           HtmlPage.Window.Invoke("calljs","Invokes"); 
  4.       } 
  5.  
  6.       private void Button_Click_3(object sender, RoutedEventArgs e) 
  7.       { 
  8.           //创建脚本 
  9.           ScriptObject calljs = (ScriptObject)HtmlPage.Window.GetProperty("calljs"); 
  10.           calljs.InvokeSelf("InvokeSelf"); 
  11.       } 
  12.  private void UserControl_Loaded(object sender, RoutedEventArgs e) 
  13.       { 
  14.           //js脚本 
  15.           string jsText = "function calljs(msg){alert(msg);}"
  16.           //创建脚本 
  17.           HtmlElement element = HtmlPage.Document.CreateElement("Script"); 
  18.           element.SetAttribute("type","text/javascript"); 
  19.           element.SetProperty("text",jsText); 
  20.           
  21.           //添加脚本到页面中 
  22.           HtmlPage.Document.Body.AppendChild(element); 
  23.  
  24.       } 

这里用了两种方法来调用js脚本.其效果一样的. 两个方法分别是 Invoke 和InvokeSelf.

10,在javascript 调用Silverlight

通过创建一个矩形来演示操作  C#;

  1. public UserControl1() 
  2.         { 
  3.             // 为初始化变量所必需 
  4.             InitializeComponent(); 
  5.  
  6.             HtmlPage.RegisterScriptableObject("Builder",this); 
  7.         } 
  8.  
  9. //定义这个方法为脚本成员 
  10.         [ScriptableMember] 
  11.         public void CreateRect(int width,int height)  
  12.         { 
  13.             Rectangle rect = new Rectangle(); 
  14.             rect.Width = width; 
  15.             rect.Height = height; 
  16.             rect.Fill = new SolidColorBrush(Colors.Blue); 
  17.             this.canvase.Children.Clear(); 
  18.             this.canvase.Children.Add(rect); 
  19.         } 

javascript: 

  1. <script type="text/javascript"function createRect() { var xamlObj = document.all("XamlObject"); xamlObj.content.Builder.CreateRect(document.all("txtWidth").value, document.all("txtHeight").value); } </script>  

HTML:

  1. <div> 
  2.             宽度:<input type="text" id="txtWidth" /> 
  3.             高度:<input type="text" id="txtHeight" /> 
  4.             <input type="button"  value="改变" onclick="createRect()" /> 
  5.            </div> 

效果. 大家ctrl+c --Ctrl+v 可以试试...
注:以上代码需要引用System.Windows.Browser;这个命名空间  

本站热点业务

更多模板/案例展示

关于我们 | 联系我们 | 团队日志 | 网站地图 | 网站合作