WP 页面间三种参数传递

来源:互联网 发布:mac怎么安装zip文件 编辑:程序博客网 时间:2024/06/08 03:03

第一种:利用QueryString

NavigationService.Navigate(new Uri("/page/Page2.xaml?name
=chengzi&age=21", UriKind.Relative));//导航到Page2.xaml页面,参数为多参数传递

Page2.xaml.cs后台代码,读取传入的参数

string str = NavigationContext.QueryString["name"].ToString();//读取传入的第一个参数 str += NavigationContext.QueryString["age"].ToString();//读取传入的第二个参数 MessageBox.Show(str);//弹出第二个参数 }


第二种:利用Resources
App.xaml
<Application.Resources>
        <nav:UriMapper  x:Key="uriMapper">
         //传递多个参数,这里要记住传递参数的格式
       <nav:UriMapping Uri="Page2/{mm},{nn}"  MappedUri="/page/Page2.xaml?Name={mm},Age={nn}"></nav:UriMapping>
        </nav:UriMapper>
</Application.Resources>

这里需要注意的的前面的mm以及nn和后面mm以及nn必须是相同的
App.xaml.cs


this.RootFrame.UriMapper = Resources["uriMapper"] as UriMapper;//在App的构造函数中调用

调用页面导航函数,并传递参数

 NavigationService.Navigate(new Uri("Page2/chengzi,21", UriKind.Relative)); 

读取传递的参数,同上

第三种:页面间传递对象

Windows Phone 7 的NavigationContext.QueryString是不支持传递对象的,那么如果我们现在有个对象需要传递该如何实现呢?可以在App里面定义一个对象属性,然后这个属性就可以提供全局访问。是不是我可以理解成这个属性其实也可以放在一个公用的静态类上呢?呵呵,下面看如何实现吧
步骤一:

声明一个对象名为Model写下如何函数:
public class Model
{
public string name { get; set; }
public string file { get; set; }
}
 
然后在App.xaml.cs 里面将Model 声明为一个公用的静态属性

public static Class.Model MyAppModel { get; set; }

余下的功夫就是为其赋值和取值的操作了,点击跳往下一页的按钮时,为App.Model 赋值。
在第二页时取出App.Model的值,代码编写见下方:


private void button1_Click(object sender, RoutedEventArgs e)
{
App.MyAppModel= new Class.Model { name="chengzi",file="my"};
NavigationService.Navigate(new Uri("/page1.xaml",UriKind.Relative));
}
 
第二页Loaded完毕后:
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
    //读取App中定义的全局对象
    string name = App.MyAppModel.name;
            name += "//";
            name += App.MyAppModel.file;
            MessageBox.Show(name);
}
 
原创粉丝点击