微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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,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,string > parameters = e.InitParams;

    this .RootVisual = new Page1 (parameters);

}

@H_404_412@ XAML 页面使用 IDictionary 参数

@H_404_412@如果你按上述步骤设置正确,你将可以在 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" ];

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐