Разработка приложений для Windows Phone 7

Навигация между страницами с помощью Silverlight

Показывать лекцию целиком

Дополнительные материалы к занятию можно скачать здесь.

Сегодня мы рассмотрим навигацию между страницами в Windows Phone 7 Silverlight приложениях. Данная тема важна по 2 причинам. Во-первых, Windows Phone 7 приложения практически всегда состоят из нескольких страниц, а во-вторых все телефоны на Windows Phone 7 имеют аппаратную кнопку "Назад", что позволяет пользователям легко возвращаться на предыдущую страницу [28].

Навигация между страницами на телефоне напоминает таковую в Web приложениях. И, хотя, в случае с телефоном, у нас есть больший контроль над навигацией, с точки зрения пользователя различия минимальны. Более того, любое Silverlight приложение для Windows Phone 7 состоит как минимум из одной страницы, тогда как традиционные Silverlight приложения состоят как минимум из одного пользовательского элемента управления (UserControl), внутри которого может быть фрейм для навигации между страницами [28].

Упражнение 16.1. Навигация между xaml-документами

Далее, мы познакомимся с навигацией между различными xaml-документами. Для этого нам потребуется внести изменение в файл MainPage.xaml. Вот его код:

<phone:PhoneApplicationPage 
    x:Class="p8_1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Навигация между страницами" 
             Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Указы Петра I" Margin="9,-7,0,0" 
              Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel>
                <HyperlinkButton Content="Указ №1" NavigateUri="/Peter_1.xaml"/>
                <HyperlinkButton Content="Указ №2" NavigateUri="/Peter_2.xaml"/>
                <HyperlinkButton Content="Указ №3" NavigateUri="/Peter_3.xaml"/>
            </StackPanel>
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>
    

После этого нам потребуется добавить три xaml-документа следующим образом: Название проекта -> Solution Explorer -> Add -> New Item -> Online Templates -> Windows Phone Portrait Page -> Имя документа

Приведем фрагменты кода xaml-документов:

Peter_1.xaml

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Указ Петра I" 
             Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="О достоинстве гостевом" Margin="9,-7,0,0" 
              Style="{StaticResource PhoneTextTitle1Style}" FontSize="40" />
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBlock Text="Перед появлением многонародным гостю надлежит быть:
1. Мыту старательно, без пропускания оных мест.
2. Бриту тщательно, дабы нежностям дамским щетиною мерзкой урон не нанести.
3. Голодну наполовину и пьяну самую малость, а то и вовсе.
4. Обряженным вельми, но без лишнего перебору, окромя дам прелестных. 
Последним дозволяется умеренно косметикою образ свой обольстительно украсить. 
Особливо грацией, веселием и добротой от грубых кавалеров отличительными быть.
5. В освещённом зале возникнув вдруг - духом не падай, телом не дубей, напротив, - 
округлив руки и не мешкая в кипение гостевое со рвением включайся.
6. В гости придя, с расположением дома ознакомься заранее на легкую голову, 
особливо отметив расположение клозетов, а сведения эти в ту часть разума отложи, 
коя винищу менее остальных подвластна." TextWrapping="Wrap" />

        </Grid>
    </Grid>
    
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
        <TextBlock x:Name="ApplicationTitle" Text="Указ Петра I" 
         Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock x:Name="PageTitle" Text="О достоинстве гостевом" Margin="9,-7,0,0" 
          Style="{StaticResource PhoneTextTitle1Style}" FontSize="40" />
    </StackPanel>

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <TextBlock Text="Перед появлением многонародным гостю надлежит быть:
1. Мыту старательно, без пропускания оных мест.
2. Бриту тщательно, дабы нежностям дамским щетиною мерзкой урон не нанести.
3. Голодну наполовину и пьяну самую малость, а то и вовсе.
4. Обряженным вельми, но без лишнего перебору, окромя дам прелестных. 
Последним дозволяется умеренно косметикою образ свой обольстительно украсить. 
Особливо грацией, веселием и добротой от грубых кавалеров отличительными быть.
5. В освещённом зале возникнув вдруг - духом не падай, телом не дубей, напротив, - 
округлив руки и не мешкая в кипение гостевое со рвением включайся.
6. В гости придя, с расположением дома ознакомься заранее на легкую голову, 
особливо отметив расположение клозетов, а сведения эти в ту часть разума отложи, 
коя винищу менее остальных подвластна." TextWrapping="Wrap" />

    </Grid>
</Grid>
    

Peter_2.xaml

<!--LayoutRoot is the root grid where all page content is placed-->
 <Grid x:Name="LayoutRoot" Background="Transparent">
     <Grid.RowDefinitions>
         <RowDefinition Height="Auto"/>
         <RowDefinition Height="*"/>
     </Grid.RowDefinitions>

     <!--TitlePanel contains the name of the application and page title-->
     <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
         <TextBlock x:Name="ApplicationTitle" Text="Указ Петра I" 
          Style="{StaticResource PhoneTextNormalStyle}"/>
         <TextBlock x:Name="PageTitle" Text="от 09.12.1709 г." Margin="9,-7,0,0" 
           Style="{StaticResource PhoneTextTitle1Style}"/>
     </StackPanel>

     <!--ContentPanel - place additional content here-->
     <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
         <TextBlock Text="Подчиненный перед лицом начальствующим должен иметь вид лихой и придурковатый, 
         дабы разумением своим не смущать начальство..." TextWrapping="Wrap" />
     </Grid>
 </Grid>
    

Peter_3.xaml

<!--LayoutRoot is the root grid where all page content is placed-->
 <Grid x:Name="LayoutRoot" Background="Transparent">
     <Grid.RowDefinitions>
         <RowDefinition Height="Auto"/>
         <RowDefinition Height="*"/>
     </Grid.RowDefinitions>

     <!--TitlePanel contains the name of the application and page title-->
     <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
         <TextBlock x:Name="ApplicationTitle" Text="Указ Петра I" 
           Style="{StaticResource PhoneTextNormalStyle}"/>
         <TextBlock x:Name="PageTitle" Text="Об офицерах" Margin="9,-7,0,0" 
          Style="{StaticResource PhoneTextTitle1Style}"/>
     </StackPanel>

     <!--ContentPanel - place additional content here-->
     <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
         <TextBlock Text="Офицерам полков пехотных верхом на лошадях в расположение 
         конных частей являться запрет кладу, ибо они своей гнусной посадкой, 
         как собака на заборе сидя, возбуждают смех в нижних чинах кавалерии, 
         служащий к ущербу офицерской чести" TextWrapping="Wrap" />
     </Grid>
 </Grid>
    

Упражнение 16.2. Навигация с помощью кнопок. Математические функции

В данной работе навигацию между xaml-документами мы будем осуществлять с помощью элемента управления Button.

Создаем новый проект MS Windows Phone.

Код MainPage.xaml:

<phone:PhoneApplicationPage 
    x:Class="p8_2.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Навигация" 
              Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Математика" Margin="9,-7,0,0" 
             Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button Name="square_root" Click="square_root_Click" Margin="0,0,0,514"
              Content="Решение квадратного уравнения"></Button>
            <Button Name="number_order" Click="number_order_Click" Margin="0,74,0,440" C
             ontent="Нахождение порядка числа
                    "></Button>
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>
    

Код MainPage.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace p8_2
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void square_root_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/SquareRoot.xaml", UriKind.Relative));
        }

        private void number_order_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/NumberOrder.xaml", UriKind.Relative));
        }

    }
}
    

Добавляем два xaml-документа: SquareRoot.xaml и NumberOrder.xaml. Первый документ решает квадратное уравнение, второй - определяет порядок вводимого числа.

SquareRoot.xaml (Основной фрагмент)

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Решение квадратного уравнения" 
              Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Математика" Margin="9,-7,0,0" 
              Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,132">
            <TextBox Name="txtA" Margin="0,6,0,400" />
            <TextBox Name="txtB" Margin="0,62,0,344" />
            <TextBox Name="txtC" Margin="0,118,0,288"  />
            <Button Name="bttnCalculate" Click="bttnCalculate_Click" 
              Content="Рассчитать!" Margin="0,199,0,190" />
            <ContentControl Name="cnt1" Margin="0,291,0,0" />
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>
    

SquareRoot.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace p8_2
{
    public partial class SquareRoot : PhoneApplicationPage
    {
        public SquareRoot()
        {
            InitializeComponent();
        }

        private void bttnCalculate_Click(object sender, RoutedEventArgs e)
        {
            double a, b, c, d, x1, x2;
            string str;
            a = System.Convert.ToDouble(txtA.Text);
            b = System.Convert.ToDouble(txtB.Text);
            c = System.Convert.ToDouble(txtC.Text);
            d = Math.Pow(b, 2) - 4 * a * c;

            if (d < 0) { str = "Действительных корней нет!"; }
            else
            {
                x1 = (-b - Math.Sqrt(d)) / (2 * a);
                x2 = (-b + Math.Sqrt(d)) / (2 * a);
                str = "x1 = " + x1 + "\nx2 = " + x2;
            }
            cnt1.Content = str;

        }

    }
}
    

NumberOrder.xaml (основной фрагмент)

<!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Нахождение порядка числа" 
              Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Математика" Margin="9,-7,0,0" 
              Style="{StaticResource PhoneTextTitle1Style}" FontSize="72" />
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBox Name="txtNumber" Margin="0,6,0,519" />
            <Button Name="bttnCalculate" Click="bttnCalculate_Click" 
              Content="Рассчитать!" Margin="-6,105,6,423" />
            <ContentControl Name="cnt1" Margin="0,200,0,0" />
        </Grid>
    </Grid>
    

NumberOrder.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace p8_2
{
    public partial class NumberOrder : PhoneApplicationPage
    {
        public NumberOrder()
        {
            InitializeComponent();
        }

        private void bttnCalculate_Click(object sender, RoutedEventArgs e)
        {
            Int64 number, order;
            string str;
            number = System.Convert.ToInt64(txtNumber.Text);
            order = 0;
            str = "Число: " + number;
            while (number > 0)
            {
                order++;
                number /= 10;
            };
            str += "\nПорядок величины: " + order;
            cnt1.Content = str;

        }
    }
}
    
Вернуться к учебному плану