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

Знакомство с XAML

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

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

Вложенные файлы: Presentation_6.pptx

Вложенные папки: Lecture_6_1, Lecture_6_2, Lecture_6_3, Lecture_6_4, Lecture_6_5, Lecture_6_6, Lecture_6_7

XAML широко используется в .NET Framework 4.0, в особенности в Windows Presentation Foundation (WPF) и Windows Workflow Foundation (WF). В WPF XAML используется как язык разметки пользовательского интерфейса, для определения элементов пользовательского интерфейса, привязки данных, поддержки событий и др. свойств. В WF, при помощи XAML можно определять последовательности выполняемых действий (workflows).

XAML файлы можно создавать и редактировать при помощи инструментов визуального конструирования, таких как: Microsoft Expression Blend, Microsoft Visual Studio, WPF Visual Designer. Все созданное или реализованное в XAML может быть выражено при помощи более традиционных .NET языков, таких как: C# или Visual Basic.NET. Однако ключевым аспектом технологии является уменьшение сложности используемых для обработки XAML инструментов, так как XAML основан на XML. В результате чего, появляется множество продуктов, создающих основанные на XAML приложения. Поскольку XAML базируется на XML, у разработчиков и дизайнеров появилась возможность одновременно работать над содержимым без необходимости компиляции.

Рассмотрим несколько примеров использования Xaml.

9.1. Программирование двухмерной графики

Во-первых, с помощью языка расширенной разметки для приложений можно программировать двухмерную графику.

Пример 9.1. Изображение эллипса

Создаем проект Windows Presentation Foundation. Назовем проект Lecture_6_1.

В окне MainWindow.xaml наберите следующий код:

<Window x:Class="Lecture_6_1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Canvas>
        <Ellipse Name="e1" Fill="AliceBlue" Stroke="BlueViolet" Width="200" Height="150"
   Canvas.Left="20" Canvas.Top="30"></Ellipse>
    </Canvas>
</Window>
        

Получаем следующий результат:

Документ MainPage.xaml является xml-документом с корневым элементом <Window…>. Приложения с таким корневым элементам являются типичными Windows-приложениями. Их широкое распространение началось с Windows Vista. Помимо Window существует также корневой элемент <Page…>. При его использовании можно добиться интересных результатов, например, можно разрабатывать приложения со страничной организацией (как в web-сайте).

Кстати сказать, результата похожего на пример 1 можно добиться, рисуя эллипс программно.

Пример 9.2. Программное рисование фигур

Создаем приложение WPF Lecture_6_2.

Код MainWindow.xaml:

<Window x:Class="Lecture_6_2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Canvas Name="c1"/>
    </Grid>
</Window>
        

Код MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Lecture_6_2
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            CreateEllipse();
        }

        private void CreateEllipse()
        {
            // Создаем эллипс
            Ellipse blueRectangle = new Ellipse();
            blueRectangle.Height = 150;
            blueRectangle.Width = 200;

            // Создаем  кисти
            SolidColorBrush blueBrush = new SolidColorBrush();
            blueBrush.Color = Colors.AliceBlue;
            SolidColorBrush blackBrush = new SolidColorBrush();
            blackBrush.Color = Colors.BlueViolet;

            // Задаем цвет и ширину эллипса
            blueRectangle.StrokeThickness = 1;
            blueRectangle.Stroke = blackBrush;
            // Fill rectangle with blue color
            blueRectangle.Fill = blueBrush;

            // Добавляем эллипс к холсту
            c1.Children.Add(blueRectangle);
        }

    }
}
        

Получаем следующий результат:

Пример 9.3. Знакомство с классом Geometry. Рисование эллипса

Большими возможностями обладает класс Geometry. С его помощью можно создавать сложную графику, например, можно объединять несколько объектов в один "путь" (Path). Но мы начнем с простого примера.

Создаем проект Lecture_6_3.

В окне MainWindow.xaml наберите следующий код:

<Window x:Class="Lecture_6_3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Path Fill="Gainsboro" Stroke="Blue">
            <Path.Data>
                <EllipseGeometry Center="50,90" RadiusX="30" RadiusY="80">
                </EllipseGeometry>
            </Path.Data>
        </Path>
    </Grid>
</Window>
        

Получаем следующий результат:

Пример 9.4. Изображение восьми спутников ГЛОНАСС, расположенных в одной из плоскостей

Создаем проект Lecture_6_4.

В окне MainWindow.xaml наберите следующий код:

<Window x:Class="Lecture_6_4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="650" Width="650">
    <Canvas>
        <Path Fill="Gainsboro" Stroke="Blue">
            <Path.Data>
                <GeometryGroup>
                    <EllipseGeometry Center="620,320" RadiusX="10" RadiusY="10"></EllipseGeometry>
                    <EllipseGeometry Center="532,107" RadiusX="10" RadiusY="10"></EllipseGeometry>
                    <EllipseGeometry Center="320,20" RadiusX="10" RadiusY="10"></EllipseGeometry>
                    <EllipseGeometry Center="107,107" RadiusX="10" RadiusY="10"></EllipseGeometry>
                    <EllipseGeometry Center="20,320" RadiusX="10" RadiusY="10"></EllipseGeometry>
                    <EllipseGeometry Center="107,532" RadiusX="10" RadiusY="10"></EllipseGeometry>
                    <EllipseGeometry Center="320,620" RadiusX="10" RadiusY="10"></EllipseGeometry>
                    <EllipseGeometry Center="532,532" RadiusX="10" RadiusY="10"></EllipseGeometry>

                </GeometryGroup>
            </Path.Data>
        </Path>
    </Canvas>

</Window>
        

Получаем следующий результат:

В данном примере показана возможность объединения восьми эллипсов в один объект Path.

Пример 9.5. Изображение 24-х спутников ГЛОНАСС в одной плоскости

Создаем проект practice_6_5. Изображение 24-х спутников ГЛОНАСС

В следующем примере показаны в одной плоскости спутники системы ГЛОНАСС. Спутники на каждой плоскости сдвинуты на 15 градусов.

В окне MainWindow.xaml наберите следующий код:

<Window x:Class="Lecture_6_5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="650" Width="650">
    <Window.Resources>
        <GeometryGroup x:Key="Geometry">
            <EllipseGeometry Center="580,300" RadiusX="10" RadiusY="10"></EllipseGeometry>

            <EllipseGeometry Center="580,300" RadiusX="10" RadiusY="10">
                <EllipseGeometry.Transform>
                    <RotateTransform CenterX="300" CenterY="300" Angle="45"></RotateTransform>
                </EllipseGeometry.Transform>
            </EllipseGeometry>

            <EllipseGeometry Center="580,300" RadiusX="10" RadiusY="10">
                <EllipseGeometry.Transform>
                    <RotateTransform CenterX="300" CenterY="300" Angle="90"></RotateTransform>
                </EllipseGeometry.Transform>
            </EllipseGeometry>

            <EllipseGeometry Center="580,300" RadiusX="10" RadiusY="10">
                <EllipseGeometry.Transform>
                    <RotateTransform CenterX="300" CenterY="300" Angle="135"></RotateTransform>
                </EllipseGeometry.Transform>
            </EllipseGeometry>

            <EllipseGeometry Center="580,300" RadiusX="10" RadiusY="10">
                <EllipseGeometry.Transform>
                    <RotateTransform CenterX="300" CenterY="300" Angle="180"></RotateTransform>
                </EllipseGeometry.Transform>
            </EllipseGeometry>

            <EllipseGeometry Center="580,300" RadiusX="10" RadiusY="10">
                <EllipseGeometry.Transform>
                    <RotateTransform CenterX="300" CenterY="300" Angle="225"></RotateTransform>
                </EllipseGeometry.Transform>
            </EllipseGeometry>

            <EllipseGeometry Center="580,300" RadiusX="10" RadiusY="10">
                <EllipseGeometry.Transform>
                    <RotateTransform CenterX="300" CenterY="300" Angle="270"></RotateTransform>
                </EllipseGeometry.Transform>
            </EllipseGeometry>

            <EllipseGeometry Center="580,300" RadiusX="10" RadiusY="10">
                <EllipseGeometry.Transform>
                    <RotateTransform CenterX="300" CenterY="300" Angle="315"></RotateTransform>
                </EllipseGeometry.Transform>
            </EllipseGeometry>
        </GeometryGroup>
    </Window.Resources>

    <Canvas>
        <Path Fill="Red" Stroke="Black" Data="{StaticResource Geometry}">
        </Path>

        <Path Fill="Green" Stroke="Blue" Data="{StaticResource Geometry}">
            <Path.RenderTransform>
                <RotateTransform CenterX="300" CenterY="300" Angle="15"></RotateTransform>
            </Path.RenderTransform>
        </Path>

        <Path Fill="Blue" Stroke="Blue" Data="{StaticResource Geometry}">
            <Path.RenderTransform>
                <RotateTransform CenterX="300" CenterY="300" Angle="30"></RotateTransform>
            </Path.RenderTransform>
        </Path>
    </Canvas>
</Window>
        

Получаем следующий результат:

В примере показана возможность использования ресурсов. Первые восемь спутников, обозначенных эллипсами, помещаются в ресурс, потом этот ресурс дважды смещается на разные углы.

Пример 9.6. Элемент управлениям InkCanvas

В данной работе мы познакомимся с элементом управления, позволяющим рисовать.

Создаем проект Lecture_6_6.

В окне MainWindow.xaml наберите следующий код:

<Window x:Class="Lecture_6_6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <InkCanvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"/>
    </Grid>
</Window>
        

Получаем следующий результат:

9.2. Разработка интерфейса приложения

На смену традиционным Windows Forms постепенно приходит технология WPF. С помощью xaml можно создавать программы с очень красочным интерфейсом. Рассмотрим пример программы-переводчика. Интерфейс был создан по мотивам приложения, описанного в книге Мэтью Мак-Дональда [20].

Создаем приложение Lecture_6_7.

Код MainWindow.xaml:

<Window x:Class="Lecture_6_7.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid Name="grid1">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBox Name="txtQuestion" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" 
  Margin="10,10,13,10" TextWrapping="Wrap" Grid.Row="0" 
  FontFamily="Verdana" FontSize="24" Foreground="Green">
            Введите слово по-английски
        </TextBox>

        <Button VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,0,0,20" Width="127" 
  Height="23" Name="cmdAnswer" 
  Click="cmdTranslate_Click" Grid.Row="1">
            Перевести
        </Button>

        <TextBox VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="10,10,13,10" 
  Name="txtAnswer" TextWrapping="Wrap" 
  IsReadOnly="True" FontFamily="Verdana" 
   FontSize="24" Foreground="Green" 
    Grid.Row="2">
            Здесь будет перевод
        </TextBox>
        <Grid.Background>
            <LinearGradientBrush>
                <LinearGradientBrush.GradientStops>
                    <GradientStop Offset="0.00" Color="Red"/>
                    <GradientStop Offset="0.50" Color="Indigo"/>
                    <GradientStop Offset="1.00" Color="Violet" />
                </LinearGradientBrush.GradientStops>
            </LinearGradientBrush>
        </Grid.Background>
    </Grid>

</Window>
    

Код MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Lecture_6_7
{
    class AnswerGenerator
    {
        string str;
        public string getTranslate(string Question)
        {
            switch (Question)
            {
                case "Apple": str = "Яблоко"; break;
                case "Lemon": str = "Лимон"; break;
                case "Orange": str = "Апельсин"; break;
                case "Mellon": str = "Дыня"; break;
                case "Water": str = "Вода"; break;
                case "Bred": str = "Хлеб"; break;
                case "Butter": str = "Масло"; break;
            }
            return str;
        }
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void cmdTranslate_Click(object sender, RoutedEventArgs e)
        {
            AnswerGenerator generator = new AnswerGenerator();
            txtAnswer.Text = generator.getTranslate(txtQuestion.Text);
        }
    }

}
    

Результат:

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