Windows Phone开发之xaml传值交互与控件hyperlinkButton的使用
mainpanel-->跳转到panel1.mainpanel有两个uri连接,分别传递不同的值;panel接收传递的参数,在textblock中显示出来。
界面如下:
代码如下:
<grid x:name="contentpanel" grid.row="1" margin="12,0,12,0">
<hyperlinkbutton content="跳转"
height="46"
horizontalalignment="left"
margin="57,41,0,0"
name="hyperlinkbutton1"
verticalalignment="top"
width="291"
navigateuri="/phoneapp5;component/page1.xaml?id=8" />
<hyperlinkbutton content="跳转2"
height="46"
horizontalalignment="left"
margin="57,93,0,0"
name="hyperlinkbutton2"
navigateuri="/phoneapp5;component/page1.xaml?id=88"
verticalalignment="top" width="291" />
<textbox height="72"
horizontalalignment="left"
margin="6,176,0,0"
name="textbox1"
text=""
verticalalignment="top"
width="460" />
</grid>
解释:
navigateuri="/phoneapp5;component/page1.xaml?id=8" 表示跳转的路径("/项目名称;component/目标xaml?传递参数"),类似url
panel1.xaml接收:
[html]
方法一:
if (this.navigationcontext.querystring.containskey("id"))
{
textblock1.text = string.format("您的id编号是:{0}", navigationcontext.querystring["id"]);
}
方法二:
string id = "";
if (this.navigationcontext.querystring.trygetvalue("id", out id))
{
textblock1.text = string.format("您的id编号是:{0}", id);
}
else {
textblock1.text = "没有找到您要找的东西哦!";
}
问题来了:
当根据需要时,进入了panel1界面,但是我想back到上个界面时,如果用手机back键没有问题,但是如果通过一个hyperlinkbutton来实现呢,textbox内容会被清空了,这不是我们想要的结果。
原因:hyperlinkbutton定位到一个新的界面时,会new一个新的实例,因此与原来的窗体在数据表现上就会不同了。
通过hyperlinkbutton还想达到back的目的,方法如下:
将界面“表单”内容写入phoneapplicationservice.state中保存。在mainpanel中重写以下方法(phoneapplicationservice需要添加引用):
[html]
phoneapplicationservice myphoneapplicationservice = phoneapplicationservice.current;
protected override void onnavigatedfrom(system.windows.navigation.navigationeventargs e)
{
myphoneapplicationservice.state["node"] = textbox1.text.tostring();
base.onnavigatedfrom(e);
}
protected override void onnavigatedto(system.windows.navigation.navigationeventargs e)
{
if (myphoneapplicationservice.state.containskey("node")) {
textbox1.text = myphoneapplicationservice.state["node"].tostring();
base.onnavigatedto(e);
}
}
摘自 whuarui2010的专栏