Silverlight入门学习(22)

原文地址: http://www.dingos.cn/index.php?topic=2000.0

第二十二章   如何从 Asp.NET 页面传递参数到 Silverlight 控件?

可以从 aspx 页面和 html 页面传递参数给 Silverlight 控件。这章介绍如 何从 aspx 页面和后置代码文件中传递参数到 Silverlight

InitParameters

Xaml 页面中用户控件有一个属性叫做 InitParameters 。可以从 Aspx 页面以键 - 值 对的形式设置值。这个属性可以接受键 - 值对,可以传递任意一组 string 值。

如何设置 InitParameters

示例 Aspx 页面设置 InitParameters 属性:

< asp : Silverlight ID ="Xaml1" runat ="server"

    Source ="~/ClientBin/MySilverlightApp.xap"

    InitParameters ="City=Houston,State=Texas,Country=USA"

    Width ="300" Height ="300" />

也可以从 Aspx 页面的后置代码文件设置这个属性。
示例 从后置代码文件设置 InitParameters 属性:

Xaml1.InitParameters = "City=Houston,State=Texas,Country=USA" ;

如何检索 InitParameters 的值?

通过 InitParameters 属性传递给 Silverlight 控件的值可以从 App.xaml 页面的 Application_Startup 事件中检索。

private void Application_Startup(object sender, StartupEventArgs e) {

    IDictionary <string , string > parameters = e.InitParams;

    this .RootVisual = new Page1 ();

}

现在,在大多数情况 下,想传递值到 xaml 页面,而不是在 App.xaml 做任何事情。

App.xaml 传递参数到其他页面

App.xaml 页面传递参数到其他页面,需要修改 xaml 页面类的构造方法来接收参数。

private IDictionary <string , string > parameters = null ;

public Page1() { InitializeComponent(); }

public Page1(IDictionary <string , string > p) {

    this .parameters = p;

    InitializeComponent();

}

上面示例显示一个附 加的构造反复添加了类型为 IDictionary 的参数并为成员设置值。

现在回到 App.xaml 传递参数给页面:

private void Application_Startup(object sender, StartupEventArgs e) {

    IDictionary <string , string > parameters = e.InitParams;

    this .RootVisual = new Page1 (parameters);

}

XAML 页面使用 IDictionary 参数

如果你按上述步骤设置正确,你将可以在 XAML 页面访问 IDictionary 的值。

textblock1.Text = this .parameters["City" ];

XAML 页面完整代码

< UserControl x : Class ="MySilverlightApp.Page1"

     xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

     xmlns : x ="http://schemas.microsoft.com/winfx/2006/xaml"

     Width ="400" Height ="300">

    < Grid x : Name ="LayoutRoot" Background ="White">

        < TextBlock x : Name ="textblock1" Width ="200" Height ="30"></ TextBlock >

    </ Grid >

</ UserControl >

page1.xaml 的后置代码文件中,可以为 textblock1 控件设置文本,如下 显示:

private void UserControl_Loaded(object sender, RoutedEventArgs e) {

    textblock1.Text = parameters["City" ];

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜晚回家

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值