[windows phone开发]导航(传参)

来源:互联网 发布:ipad版的淘宝微淘在哪 编辑:程序博客网 时间:2024/05/21 02:32


windows phone开发——导航(传参)


   当应用进行页面转换时,有时需要将不同的页面的参数,传递到另外一个页面,接着昨天的实验,今天介绍两种在页面间传参的方法。

   昨天的链接windows phone开发——导航。

   这次利用一个HyperLinkButton 和一个Button进行实验。

   在首页进行一些相应更改定义一个textblock进行说明,定义一个textbox来进行参数的传递,在Page2,Page3中分别添加一个textblock来显示所传递的参数。

MainPage

  <TextBlock  Text="点击The second page 按钮通过NavigationService.Navigate传递参数 ,点击the third page 按钮通过全局变量传递参数" Grid.Row="3" FontSize="30" TextWrapping="Wrap" Margin="10"/>            <TextBox x:Name="textbox1" Grid.Row="4" HorizontalContentAlignment="Center" Text="输入要传递的数据(通过全局变量传递)" Margin="10,10,10,50" TextWrapping="Wrap"/>

Page2

  <TextBlock Name="textblock1" Text="hello" FontSize="30" Margin="20" TextWrapping="Wrap"/>

Page3

 <TextBlock Name="textblock1"  Margin="20" Text="hello" FontSize="30" TextWrapping="Wrap"/>

  首先介绍第一种方法:通过全局变量来进行参数传递

 首先添加一个类来存储我们要传递的参数,可以根据需要定义类的成员

 public class All    {        public All()        {        }        public string str { get; set; }    }


然后再App.xaml.cs中定义一个All的全局实例

 public All s = new All();
接下来就可以利用全局实例进行参数传递了

  在想要传递的页面添加后台代码(传出页面)

 (App.Current as App).s.str = textbox1.Text;

(传入页面)
 textblock1.Text = (App.Current as App).s.str;
第二种方法:使用Navigation.Navigate进行传递
要知道Uri不仅可以传递文件地址,还可以传递字符格式
通过对HyperLinkButton的Navigate.uri就可以完成参数的传递
<pre class="html" name="code">  <HyperlinkButton x:Name="button1" HorizontalAlignment="Center" Margin="0,10,0,10" Content="The second page" FontSize="30"  NavigateUri="/Page2.xaml?key=我是通过NavigationService.Navigate传递过来的" />

其中?为参数声明的开始,如果我们要传递多个参数可以使用&进行连接
定义玩之后我们就可以是通过NavigateContext读取多要传递的参数
 textblock1.Text = NavigationContext.QueryString["key"];

至此,两种方法介绍完毕,取中后台代码的实现均可以在重写OnNavigationFrom和OnNavigationTo函数内实现。


0 0