windows phone:基本导航

Silverlight导航系统解析
本文通过一个具体的示例,展示了如何在Silverlight for 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.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));

这时你不断地按每个页面上的TextBlock就会创建一个交替存放MainPage和Page1各个实例的栈,每一个都拥有其独特的颜色。这样就需要使用手机的Back按键一步步地返回所有页面,直至最终退出应用程序为止。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值