日期:2014-05-17  浏览次数:20668 次

windows phone:页面间传递数据

页面间传递数据包括两个问题
1、如何从源页面传递数据到目标页面?

下面例子提供解决上面问题的方案。

源页面MainPage.xaml内容区域包含一个TextBlock,如

<TextBlock HorizontalAlignment="Center" Name="txt1" Text="navigate to 2nd page" VerticalAlignment="Center" ManipulationStarted="txt1_ManipulationStarted" />

MainPage.xaml.cs代码如下所示:

namespace PhoneApp2
{
    public partial class MainPage : PhoneApplicationPage
    {
        Random rand = new Random();
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
        }

        private void txt1_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            String destination = "/Page1.xaml";
            if (this.ContentPanel.Background is SolidColorBrush)
            {
                Color clr = (this.ContentPanel.Background as SolidColorBrush).Color;
                destination += String.Format("?Red={0}&Green={1}&Blue={2}",clr.R,clr.G,clr.B);
            }
            this.NavigationService.Navigate(new Uri(destination, UriKind.Relative));//导航至指定页面
            e.Complete();
            e.Handled = true;
        }
        protected override void OnManipulationStarted(ManipulationStartedEventArgs e)
        {//当触摸到页面里textblock以外的部分时,contentpanel的背景会变成随机颜色。
            this.ContentPanel.Background = new SolidColorBrush(Color.FromArgb(255, (byte)rand.Next(255), (byte)rand.Next(255), (byte)rand.Next(255)));//设置背景颜色
            base.OnManipulationStarted(e);
        }
    }
}

目标页面Page1.xaml代码重写了OnNavigatedTo方法,如下所示:

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)//当该函数被调用时,页面的构造函数已经执行完毕,但是还没有执行其他的方法
        {
            IDictionary<String, String> parameters = this.NavigationContext.QueryString;
            if (parameters.ContainsKey("Red"))
       &