您的位置:首页 > 其它

Silverlight入门学习(22)

2010-04-15 14:50 363 查看
原文地址: 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"
];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: