在上一节我们知道了如何处理Windows Phone的页面导航同时也实现了两个页面之间的数据传递。在实际开发中我们还需要为两个页面传递数据。经过看官方文档和网上资料搜集,总结参数传递主要有以下的四种方式:
1、通过NavigationContext的QueryString方式;
2、通过程序的App类设置全局变量(此方法可以传递对象);
3、通过NavigationEventArgs事件类的Content属性设置;
4、通过PhoneApplicationService类的State属性。
通过NavigationContext的QueryString方式这种方式在上一节已经介绍了,在些不再描述。下面重点介绍后面三种
(一)
通过程序的App
类设置全局变量(
此方法可以传递对象)
在工程目录下新建一个”Model”的文件夹,再在这个文件夹里新建一个类:Person类
public class Person
{
public String Name { get; set; }
public int Age { get; set; }
}
然后再在App.xaml.cs文件中加上这么一段代码
public partial class App : Application
{
/// <summary>
///提供对电话应用程序的根框架的轻松访问。
/// </summary>
/// <returns>电话应用程序的根框架。</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
public static Person person { get; set; } ……..
}
再在新建的AppHome.xaml.cs文件中为页面上的按钮添加click事件
private void button1_Click(object sender, RoutedEventArgs e)
{
App.person = new Model.Person
{
Name=txt_Name.Text,
Age=Convert.ToInt32(txt_Age.Text)
};
Uri uri = new Uri("/AppData.xaml",UriKind.Relative);
NavigationService.Navigate(uri);
}
然后在AppData.xaml文件的Loaded事件中接受传递过来的值:
private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
{
if (App.person!=null)
{
tb_Name.Text = App.person.Name;
tb_Age.Text = App.person.Age.ToString();
}
}
最终实现效果:



(二) 通过NavigationEventArgs事件类的Content属性设置
ContentPage1.xaml.cs文件中:
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
var targetPage = e.Content as ContentPage2;
if (targetPage != null)
{
targetPage.StrContent =textBox1.Text;
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/ContentPage2.xaml",UriKind.Relative));
}
ContentPage2.xaml.cs中取出Content的值:
public String StrContent { get; set; }
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (StrContent != null)
{
this.tb_ContentValue.Text = StrContent;
}
}
实现的效果:


(三) 通过PhoneApplicationService类的State属性:
StatePage1.xaml.cs文件:
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
PhoneApplicationService phoneService = PhoneApplicationService.Current;
phoneService.State["param1"] = this.textBox1.Text;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/StatePage2.xaml",UriKind.Relative));
}
StatePage2.xaml.cs文件:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (PhoneApplicationService.Current.State.ContainsKey("param1"))
{
this.tb_ParamValue.Text = PhoneApplicationService.Current.State["param1"] as string;
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (NavigationService.CanGoBack)
{
NavigationService.GoBack();
}
}
实现效果:

