可以从 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">
<Gridx : Name ="LayoutRoot" Background ="White">
<TextBlockx : Name ="textblock1" Width ="200" Height ="30"></ TextBlock >
</Grid>
</ UserControl >
在 page1.xaml 的后置代码文件中,可以为 textblock1 控件设置文本,如下显示:
private void UserControl_Loaded(object sender,RoutedEventArgs e) {
textblock1.Text = parameters["City" ];
}
Silverlight入门知识学习目录