Windows Phone 7 编成之- 6.2从源页面传递数据到目的页面

Silverlight 中将Page当作对话框使用,会引起两个问题:
1. 我该如何从源page传递数据到目的page?
2. 当我回到原始page时,我该如何返回数据?
有意思的是,有一个方法用来具体解决第一个问题,但不适用于第二个问题。 我将先介绍这个方法,在后面章节,我们再介绍第二个问题的解决方案。
下面的示例程序叫SilverlightPassData。这个程序中,MainPage为SecondPage提供一个颜色值,SecondPage用这个颜色值来初始化自己的背景色。
下面是MainPage.xaml文件的内容: Silverlight Project: SilverlightPassData File: MainPage.xaml (excerpt)

VerticalAlignment="Center"
Padding="0 34"
ManipulationStarted="OnTextBlockManipulationStarted" />


MainPage后台的代码如下:
请特别关注TextBlock上的OnTextBlockManipulationStarted事件处理函数。 Silverlight Project: SilverlightSimpleNavigation File: MainPage.xaml.cs (excerpt)
public partial class MainPage : PhoneApplicationPage
{
Random rand = new Random();
public MainPage()
{
InitializeComponent();
}
void _disibledevent=> if (ContentPanel.Background is SolidColorBrush)
{
Color clr = (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));
args.Complete();
args.Handled = true;
}
protected override void _disibledevent=> Color.FromArgb(255, (byte)rand.Next(255),
(byte)rand.Next(255),
(byte)rand.Next(255)));
base.OnManipulationStarted(args);
}
}

从上面的代码,可以看出,如果ContentPanel 的Background 属性是SolidColorBrush笔刷, 就可以获得它的Color属性值。进一步将这个颜色值转化成红,绿,蓝的字符串,并跟desination字符串连接在一起。生成的新URI值如下:
“/SecondPage.xaml?Red=244&Green=43&Blue=91”
你可能已经认出来这是一个HTML查询字符串的通用格式。
在SecondPage类中,我们重载OnNavigatedTo方法: Silverlight Project: SilverlightPassData File: SecondPage.xaml.cs (excerpt)
protected override void _disibledevent=> if (parameters.ContainsKey("Red"))
{
byte R = Byte.Parse(parameters["Red"]);
byte G = Byte.Parse(parameters["Green"]);
byte B = Byte.Parse(parameters["Blue"]);
ContentPanel.Background = new SolidColorBrush(Color.FromArgb(255, R, G, B));
}
base.OnNavigatedTo(args);
}

在上述代码中,使用NavigationEvenArgs类需要引用System.Windows.Navigation 命名空间。 OnNavigatedTo方法是定义在PhoneApplicationPage类中,而各个子类可以重载这个方法。在页面被创建后,OnNavigatedTo方法就随即被调用。当然,在该方法被调用的时候,页面的构造函数已经执行过了,在这期间,几乎没有其他事件发生(但是需要提到的是在SecondPage构造函数执行后,源page中的OnNavigatedFrom方法,既MainPage.OnNavigatedFrom方法会在SecondPage.OnNavigatedTo方法之前被调用,在6.3节中,我们会讲到这个方法)。
通过NavigationContext属性,目标类可以获得调用页面的查询字符串。这个属性只有一个公共属性 QueryString, 它返回一个存放参数的字典。在上面的代码中,我们假定如果在查询字符串中能找到”Red”, “Blue”和“Green” 就一定存在。 它将所有颜色字符串交给Byte.Parse处理,并重新构造Color属性。
现在,当你从MainPage导航到SecondPage,页面的背景色保持不变。当你返回到前一个页面,这个功能就不能保证了。没有像QueryString这样的内建功能能够返回从一个页面返回数据到另外一个页面。
Tags: 

延伸阅读

最新评论

发表评论