Silverlight 中一些必须知道的技巧【原创】

今天收集了一些silverlight 中的一些常用函数的操作...下面一一介绍

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

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

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

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

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

private void Application_Startup(object sender, StartupEventArgs e)
		{
            MainPage main = new MainPage();
            this.RootVisual = main;

            foreach (string item in e.InitParams.Keys)
            {
                main.listBox.Items.Add(new TextBlock()
                {
                    Text = String.Format("网页参数:{0} = {1}", item, e.InitParams[item])
                });
            }
           
}

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

2,sl获取URL传递参数

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

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

            BrowserInformation brow = HtmlPage.BrowserInformation;
            this.txtBlock1.Text = string.Format("浏览器名称:{0}",brow.Name);
            txtBlock1_Copy.Text = string.Format("浏览器版本:{0}", brow.BrowserVersion);
            txtBlock1_Copy1.Text = string.Format("浏览器操作系统名称:{0}", brow.Platform);
            txtBlock1_Copy2.Text = string.Format("代理字符串:{0}",brow.UserAgent);

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

   private void Button_Click(object sender, RoutedEventArgs e)
        {
            HtmlElement img = HtmlPage.Document.GetElementById("img11");

            img.SetAttribute("width",txtwidth.Text);
            img.SetAttribute("height", txtheight.Text);
        }

前台HTML代码:

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

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

5,HTML元素操作Silverlight对象

 XAML代码如下:

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

C# 代码:

public HtmlAndSilverlightDemo()
		{
			// 为初始化变量所必需
			InitializeComponent();
            HtmlElement select = HtmlPage.Document.GetElementById("sel1");

            select.AttachEvent("onchange", new EventHandler<HtmlEventArgs>(Select_onChange));
		}

        public void Select_onChange(object sender, HtmlEventArgs e) 
        {
            HtmlElement select = sender as HtmlElement;
            string value = select.GetAttribute("value");
            txtState.Text = value;
            switch (value)
            {
                case "红色":
                    this.elipse.Fill = new SolidColorBrush(Colors.Red);
                    break;
                case "绿色":
                    this.elipse.Fill = new SolidColorBrush(Colors.Green);
                    break;
                case "蓝色":
                    this.elipse.Fill = new SolidColorBrush(Colors.Blue);
                    break;
                default:
                    break;
            }
        }

HTML代码:

<div> 请选择:<select id="sel1">
<option value="红色">红色</option>
<option value="绿色">绿色</option>
<option value="蓝色">蓝色</option>
</select></div>

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

6,使用HttpUtility类

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

7,使用Document.Cookies读写Cookie

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

 #region Cookie操作

        /// <summary>
        /// 添加cookie
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetCookie(string key, string value)
        {
            DateTime expire = DateTime.UtcNow + TimeSpan.FromDays(30);
            string cookie = string.Format("{0}={1};expires={2}", key, value, expire.ToString("R"));
            HtmlPage.Document.SetProperty("cookie", cookie);
        }

        /// <summary>
        /// 获取cookie
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetCookie(string key)
        {
            key += '=';
            string[] cookies = HtmlPage.Document.Cookies.Split(';');
            foreach (string cookie in cookies)
            {
                string cookieStr = cookie.Trim();
                if (cookieStr.StartsWith(key,StringComparison.OrdinalIgnoreCase))
                {
                    //分隔出key的值
                    string[] vals = cookieStr.Split('=');
                    if (vals.Length >=2)
                    {
                        return vals[1];//返回值
                    }
                    return string.Empty;
                }
            }
            //没有找到就返回空字符串
            return string.Empty;
        }

        #endregion

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

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

消息提示:

  三种弹出窗口:

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

9,在silverlight中调用javascript

XAML代码:

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

C#:

  private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            HtmlPage.Window.Invoke("calljs","Invokes");
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            //创建脚本
            ScriptObject calljs = (ScriptObject)HtmlPage.Window.GetProperty("calljs");
            calljs.InvokeSelf("InvokeSelf");
        }
   private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            //js脚本
            string jsText = "function calljs(msg){alert(msg);}";
            //创建脚本
            HtmlElement element = HtmlPage.Document.CreateElement("Script");
            element.SetAttribute("type","text/javascript");
            element.SetProperty("text",jsText);
           
            //添加脚本到页面中
            HtmlPage.Document.Body.AppendChild(element);

        }

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

10,在javascript 调用Silverlight

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

public UserControl1()
		{
			// 为初始化变量所必需
			InitializeComponent();

            HtmlPage.RegisterScriptableObject("Builder",this);
		}

//定义这个方法为脚本成员
        [ScriptableMember]
        public void CreateRect(int width,int height) 
        {
            Rectangle rect = new Rectangle();
            rect.Width = width;
            rect.Height = height;
            rect.Fill = new SolidColorBrush(Colors.Blue);
            this.canvase.Children.Clear();
            this.canvase.Children.Add(rect);
        }

javascript:

<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:

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

效果. 大家ctrl+c --Ctrl+v 可以试试...

注:以上代码需要引用System.Windows.Browser;这个命名空间
 呼呼..好累好累..

喜欢的朋友别忘了评论哦..

太阳每一天升起来,我总是筋疲力尽..

posted on 2010-05-14 15:23  小刚qq  阅读(3575)  评论(3编辑  收藏  举报