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

windows phone:基本导航

下例是一个从一个页面(MainPage.xaml)导航到另一个页面(Page1.xaml)的Silverlight例子

在MainPage.xaml的内容区域包含一个TextBlock并对其ManipulationStarted事件注册了一个事件处理程序,如下所示:

<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)
        {
            this.NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));//导航至指定页面

            //Navigate()第一个参数是一个Uri类型的对象,第二个参数使用了UriKind.Relative来标明此Uri是相对于MainPage.xmal文件的相对位置

            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中同样包含了一个TextBlock,如下所示:

<TextBlock  HorizontalAlignment="Center"  Name="txt2" Text="go back to 1st page" VerticalAlignment="Center" ManipulationStarted="txt2_ManipulationStarted" />

Page1.xaml.cs代码:

namespace PhoneApp2
{
    public partial class Page1 : PhoneApplicationPage
    {
        public Page1()
        {
            InitializeComponent();
        }

        private void txt2_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            this.NavigationService.GoBack();//使用该方法会使程序返到导航进入Page1.xaml之前的页面,本例中是MainPage.xaml
            e.Complete();
            e.Handled = true;
        }
    }
}

运行程序,在主页面中触摸"navigate to 2nd page"则进入第二页,点击此页的"go back to 1st page"(或按下手机的back按键)则返回主页面。

Silverlight for Windows Phone的导航系统基于栈(stack),栈是一种后进先出的数据结构。把调用Navigate函数的称为源页面,把导航到的页面称为目标页面在。当源页面调用Navigate函数时,源页面被放进栈中,同时创建目标页面的新实例并显示出来。

在Silverlight程序中,除了程序在初始页面的时候,Windows Phone的Back按键与调用GoBack函数都执行相同的功能。当程序在初始页面的情况下,硬件Back按键会终止应用程序。

注:如将Page1.xaml.cs里面的GoBack调用替换成

this.NavigationS