Blank app universal windows

Начало работы. Первое приложение

Последнее обновление: 12.11.2017

Итак, начнем работу с Universal Windows Platform и создадим первый проект. Для этого откроем Visual Studio 2017 и в меню выберем пункт
File->New->Project…. Перед нами откроется окно создания нового проекта:

Проект Universal Windows Platform

В этом окне нам надо выбрать для языка C# выбрать шаблон Blank App (Universal Windows).
Внизу окна установим путь к проекту и дадим имя проекта, например, HelloApp. И нажем на кнопку OK.

После этого нам отображается с выбором тех версий SDK, на которые будет ориентировано приложение:

SDK Universal Windows Platform

Как правило, эти версии отражают глобальные обновления ОС Windows, например, Creators Update, Anniversary Update и т.д. В качестве опции
Target Version (целевой среды приложения) рекомендуется устанавливать последнюю доступную версию SDK, которая обычно уже установлена по умолчанию.
При выборе минимальной версии следует учитывать, что выбранное значение задает минимальную версию платформы UWP, с которой проект может работать.

Оставим данные опции по умолчанию и нажмем на OK. И Visual Studio создает новый проект:

Рассмотрим все узлы, из которых состоит проект:

  • AssemblyInfo.cs: файл кода на c#, который устанавливает информацию о сборке приложения

  • Default.rd.xml: файл, который содержит директивы .NET Native — технологии, которая позволяет компилировать код C# в машинный код

  • References: стандартный узел с подключенными библиотеками

  • Assets: предназначен для хранения различных ресурсов приложения. По умолчанию здесь несколько файлов изображений

  • App.xaml и App.xaml.cs: главный файл приложения с кодом XAML и связанный с ним файл кода C#. Они устанавливают
    некоторую общую логику, общие ресурсы для всего приложения

  • HelloApp_TemporaryKey.pfx: временный ключ, которым подписываются приложения во время запуска на локальном компьютере разработчика

  • MainPage.xaml и MainPage.xaml.cs: файлы главной страницы приложения — графическое представление в виде кода XAML и логика в виде
    кода C#

  • Package.appxmanifest: файл манифеста, устаналивающий различные настройки приложения

Теперь сделаем простейшее приложение. Визуально приложение UWP представлено через страницы — отдельные объекты Page. По умолчанию в проекте есть
только одна страница — MainPage. Код этой страницы и определяет то, что мы увидим на экране при запуске приложения. И теперь немного изменим ее.

Итак, откроем файл MainPage.xaml:

MainPage in Universal Windows Platform

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

Внесем небольшие изменения. Изменим код XAML на следующий:

<Page
    x:Class="HelloApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HelloApp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="Hello World!" FontSize="30" />
    </Grid>
</Page>

Суть сделанных нами изменений состоит в том, что мы добавили элемент <TextBlock Text="Hello World!" FontSize="30" /> — обычную текстовую метку с надписью
«Hello World!». И чтобы сделать текст крупным, у текстовой метки устанавливается шрифт высотой в 30 единиц. После изменения также должны произойти автоматические изменения в визуальном представлении:

Код XAML in UWP

Теперь запустим проект на выполнение, нажав на F5. И у нас отобразиться такое вот окошко, представляющее MainPage:

Первое приложение на UWP

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

Запуск на Windows 10 Mobile

Также мы можем развернуть и простестировать приложение на мобильном устройстве под управлением Windows 10 Mobile. Но для этого надо подключить мобильное устройство
к компьютеру с помощью кабеля USB, а на самом смартфоне
установить режим разработчика на телефоне можно, перейдя в Параметры ->
Обновление и безопасность -> Для разработчиков и выбрав пункт «Режим разработчика»:

Universal Windows Platform (UWP) — это платформа разработки
приложений для операционных систем Windows, охватывающая широкий спектр
устройств, включая ПК, планшеты, смартфоны, Xbox, HoloLens и другие
устройства. UWP позволяет создавать приложения с единым кодом, которые
могут работать на всех этих устройствах, адаптируя интерфейс и
функциональность в зависимости от специфики устройства.

В этой главе мы рассмотрим, как создавать UWP-приложения с
использованием Visual Basic, основные принципы и возможности, которые
предоставляет эта платформа, а также как интегрировать UWP с другими
компонентами Windows.

Основы работы с UWP

UWP-приложения могут быть разработаны с помощью Microsoft Visual
Studio, который предоставляет все необходимые инструменты для
разработки, от написания кода до тестирования и отладки. Приложения
могут быть написаны на различных языках, включая Visual Basic.

Для создания простого UWP-приложения откройте Visual Studio, создайте
новый проект и выберите тип “Blank App (Universal Windows)” с языком
программирования Visual Basic.

Пример
простого приложения на Visual Basic для UWP

Imports Windows.UI.Xaml
Imports Windows.UI.Xaml.Controls

Public NotInheritable Class MainPage
    Inherits Page

    Public Sub New()
        This.InitializeComponent()
    End Sub

    Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
        Dim message As String = "Hello, UWP!"
        MessageBox.Show(message)
    End Sub
End Class

В этом примере создается простая страница приложения с одной кнопкой,
при нажатии на которую появляется всплывающее сообщение с текстом
“Hello, UWP!”.

Работа с пользовательским
интерфейсом

Одной из особенностей UWP является использование языка разметки XAML
для создания пользовательских интерфейсов. XAML предоставляет
декларативный способ описания интерфейсов, который легко комбинируется с
кодом на Visual Basic.

Пример XAML-разметки для
кнопки

<Page x:Class="UWPApp.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:UWPApp"
      Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
        <Button Content="Click Me" HorizontalAlignment="Center" VerticalAlignment="Center" Click="Button_Click"/>
    </Grid>
</Page>

В этом примере создается страница с кнопкой, расположенной по центру.
Атрибут Click указывает на обработчик события, который
будет вызываться при нажатии на кнопку.

Основные принципы работы с
UWP

Платформонезависимость

Одна из основных особенностей UWP — это принцип “один код для всех
устройств”. Разработчик пишет приложение с использованием UWP API, и оно
автоматически адаптируется под различные устройства. Например,
приложение может быть оптимизировано для работы на экране ПК, а также
автоматически масштабироваться для смартфонов или адаптироваться для
управления с помощью жестов на устройствах с сенсорным экраном.

Адаптивность интерфейса

UWP предоставляет мощные средства для адаптации интерфейса под
различные экраны и разрешения. Использование стандартных контейнеров,
таких как Grid, StackPanel,
RelativePanel, позволяет создавать гибкие интерфейсы,
которые автоматически изменяют свое расположение в зависимости от
размера экрана.

Работа с файлами и
хранилищем данных

UWP предоставляет доступ к различным видам хранилища данных, включая
локальные файлы, библиотеку изображений, данные пользователя и облачное
хранилище через API Windows.Storage.

Пример работы с файлами

Imports Windows.Storage

Private Async Sub SaveTextToFileAsync()
    Dim folder As StorageFolder = KnownFolders.DocumentsLibrary
    Dim file As StorageFile = Await folder.CreateFileAsync("example.txt", CreationCollisionOption.ReplaceExisting)
    Await FileIO.WriteTextAsync(file, "This is a sample text.")
End Sub

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

Асинхронное программирование
в UWP

Асинхронное программирование — это важная часть разработки для UWP,
особенно для обработки операций ввода-вывода (например, чтение и запись
файлов, работа с сетью). В UWP используется ключевое слово
Async и операторы Await для асинхронных
операций.

Пример асинхронного метода

Private Async Sub DownloadData()
    Dim uri As New Uri("https://example.com/data")
    Dim client As New Windows.Web.Http.HttpClient()
    Dim result As String = Await client.GetStringAsync(uri)
    MessageBox.Show(result)
End Sub

Этот пример демонстрирует использование асинхронной операции для
загрузки данных с веб-ресурса. Метод GetStringAsync
позволяет получить строку из интернет-ресурса, не блокируя основной
поток пользовательского интерфейса.

Взаимодействие с сетью

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

Пример загрузки данных с
веб-сервиса

Private Async Sub FetchWeatherData()
    Dim uri As New Uri("https://api.openweathermap.org/data/2.5/weather?q=London&appid=your_api_key")
    Dim client As New Windows.Web.Http.HttpClient()
    Dim response As String = Await client.GetStringAsync(uri)
    ' Обработка данных ответа
    MessageBox.Show(response)
End Sub

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

Работа с сенсорными
событиями

UWP поддерживает разнообразные сенсорные устройства, такие как
тачскрины и устройства с поддержкой жестов. Для обработки событий
сенсорного ввода можно использовать классы, такие как
Pointer, GestureRecognizer и другие.

Пример обработки сенсорных
событий

Private Sub OnPointerPressed(sender As Object, e As Windows.UI.Xaml.Input.PointerRoutedEventArgs)
    Dim pointer As Windows.UI.Input.Pointer = e.Pointer
    If pointer.PointerDeviceType = Windows.Devices.Input.PointerDeviceType.Touch Then
        MessageBox.Show("Touch event detected")
    End If
End Sub

Здесь показан простой пример обработки касания экрана и вывода
сообщения при детектировании события касания.

Заключение

UWP предоставляет мощные возможности для создания универсальных
приложений для различных устройств на платформе Windows. Используя
Visual Basic, разработчики могут легко создавать адаптивные интерфейсы,
работать с асинхронными операциями, взаимодействовать с файловой
системой и использовать сенсорные устройства. Платформа UWP позволяет
создавать приложения, которые работают на разных устройствах с
минимальными изменениями в коде, что делает её отличным выбором для
разработки современных приложений на Windows.

TT Technology 2

Last week, I covered the solution stack that I’m using for a new programming project. This week, I’ll go into more detail about one aspect of it: using the Model-View-ViewModel (MVVM) pattern in Universal Windows Platform (UWP) apps.

The Blank App Template

Visual Studio 2015 provides a template called Blank App (Universal Windows) that works as a starting point for UWP app development. Rather than creating a solution for my app project right away, I’m going to first experiment with a few key features of the solution stack.

The process of starting a new UWP solution using the Blank App template happens as follows:

  • Open Visual Studio 2015
  • Click New Project…
  • Select templates — Visual C# — Windows — Universal — Blank App (Universal Windows)

VS then asks for some information about the new project and its solution. I’ll use the following values:

  • Name: UWPMain
  • Location: D:\Projects
  • Solution name: UWP-MVVM-EF-SQLite
  • Create directory for solution: Checked
  • Create new Git repository: My preference is to leave this unchecked, and manually create a Git repository from the command line, just so I’m sure about what’s going on.

Here’s the result of those settings:

Create directory for solution is useful for organizing multiple projects under a solution. It defaults to checked, and that’s usually how you should leave it. The result is that VS creates a directory under Location with the same name as the solution, and puts the solution file inside that directory. In this case, that means it creates a directory called D:\Projects\UWP-MVVM-EF-SQLite containing a file called UWP-MVVM-EF-SQLite.sln.

By default, VS suggests giving the solution and the project the same name. But if you’re planning to add more than one project to a solution, it may be more clear to keep the names separate. That’s what I have done in this case: the solution is called UWP-MVVM-EF-SQLite (foreshadowing a discussion of other components in the solution stack). And the project is called UWPMain. As a result, VS creates a D:\Projects\UWP-MVVM-EF-SQLite\UWPMain directory and puts project-specific files there.

In the last step of the New Project process, VS asks about the minimum and target versions of Windows 10 for this UWP app. The defaults are fine.

At the end of the process, we have with the following files and directories under D:\Projects:

  • UWP-MVVM-EF-SQLite: the solution directory
    • UWP-MVVM-EF-SQLite.sln: solution-specific information, and references to projects in the solution.
    • .vs: machine- and user-specific files. This directory is created automatically when the solution is loaded, so it doesn’t need to be tracked by Git.
    • UWPMain: a project directory. All project-specific files for the UWPMain project go under here.
      • UWPMain.csproj: project-level information, and references to files in the project.
      • App.xaml: app-level settings for this UWP app.
      • App.xaml.cs: C# code at the app level.
      • UWPMain_TemporaryKey.pfx: UWP apps can be uploaded to the Windows Store, and part of that process involves signing the app with a digital certificate. The UWPMain_TemporaryKey.pfx certificate is self-signed, so it is only useful for running the app locally.
      • MainPage.xaml: page-level markup for the app’s main page.
      • MainPage.xaml.cs: C# code at the page level.
      • Package.appxmanifest: According to MSDN, this file “contains the info the system needs to deploy, display, or update a Windows app.” Among other things, it includes information about the publisher (me), pointers to .png assets, and what types of devices the app targets.
      • project.json: information about project references and dependencies.
      • project.lock.json: the cached result of NuGet’s analysis of project dependencies. It gets generated automatically, so it shouldn’t be tracked by Git.
      • Assets: 7 .png files of various sizes, used for the app logo.
      • Properties\AssemblyInfo.cs: app properties, like description and version number.
      • Properties\Default.rd.xml: runtime directives for .NET Native, a VS2015 precompilation technology used for UWP apps.
      • bin and obj: directories containing the output of the compilation process.

When you run the blank app, you see a splash screen, followed by a single blank page.

Model, View, and ViewModel

In MVVM terminology, the Blank App only has a View. The template doesn’t include any Models or ViewModels. There’s nothing stopping developers from coding directly in MainPage.xaml.cs. That’s fine for simple apps, but as an app becomes more complex, there are advantages to using a more sophisticated pattern.

Let’s start with a very basic scenario: We have a Task class, and it has a Name property. That’s it. I’ll demonstrate basic XAML data binding using this single property and the MVVM pattern.

Model

The first step in writing this example app is to create the Model. In a full app, the model would contain business logic and database queries. But for this example, the Model is just one plain C# class with one string property. It is created as follows:

  • In the UWPMain project: Add — New Folder — Models
  • In the Models folder: Add — Class — Task.cs
  • Define the class as follows:

    public class Task
    {
        public string Name { get; set; }
    }
    

(We can distinguish this Task class from the .NET Framework’s System.Threading.Tasks.Task class the usual way, by using namespaces. I considered calling this class Activity instead, but there’s a System.Activities.Activity class as well. So I’m just going with the name that makes the most sense).

ViewModel

To isolate the model from user interface concerns, we’ll now create a View Model. By MVVM convention, if we have a class called Task and we need to expose its data in the UI, we create a corresponding class called TaskViewModel.

TaskViewModel will be more complex than Task, even in this simple example. That’s because the view model is responsible for setting up data binding by implementing the INotifyPropertyChanged interface.

To support data binding while keeping the view model code clean, I have taken the approach described by John Shewchuk in A Minimal MVVM UWP App: each view model class inherits from a base class, and the base class implements INotifyPropertyChanged. The base class in my example is forked from his NotificationBase class.

Here are the steps to create TaskViewModel:

  • In the UWPMain project: Add — New Folder — ViewModels
  • In the ViewModels folder: Add — Class — NotificationBase.cs
  • In the ViewModels folder: Add — Class — TaskViewModel.cs

Rather than show all of the code for these classes here, I have created a GitHub repository for it.

NotificationBase.cs contains a NotificationBase class that inherits from INotifyPropertyChanged, and a NotificationBase<T> class that inherits from NotificationBase. TaskViewModel.cs is then fairly simple. It inherits from NotificationBase<Task> and contains a private Task reference, a public constructor, and a single Name property. I’ll go into more detail below on how these three classes work.

View

The View code for this is example is located in MainPage.xaml and MainPage.xaml.cs. These files are created by the New Project wizard. They start out with some initial code, but we’ll add a few more things to demonstrate data binding.

Our data binding example has the following two components:

  • A TextBox control that the user types in.
  • A TextBlock control that receives the user’s typed input through data binding.

I also added a few additional TextBlocks that function as explanatory labels, and don’t participate in the binding process. That’s all. But despite the simplicity of the example, there’s quite a bit of detail to uncover as the binding magic happens.

To set up the view to demonstrate binding, add the following to MainPage.xaml.cs:

public TaskViewModel Task { get; set; }

Note that the View references the View Model (the TaskViewModel class). It doesn’t directly reference the Model (the Task class). The View doesn’t know that the Model exists.

In the MainPage constructor, initialize the view model property:

Task = new TaskViewModel();

Next, add the following two elements to MainPage.xaml:

<TextBox Text="{x:Bind Task.Name, Mode=TwoWay}" />
<TextBlock Text="{x:Bind Task.Name, Mode=OneWay}" />

In a UWP app, a TextBox accepts typed input in a box on the screen. Its Text property can be used to read what the user types, or display text for the user to edit. We could write something like Text="some text" to display literal text in the text box. Instead, we’re going to use the Text property to set up data binding.

{x:Bind} is a Windows 10 markup extension. It has some advantages compared to older XAML binding technology, including performance improvements (since binding happens at compile time).

For the text box, {x:Bind Task.Name, Mode=TwoWay} means we want to bind the value in the text box to Task.Name, the Name property of the TaskViewModel instance defined in MainPage.xaml.cs. And we want to bind it in TwoWay mode, meaning that changes to the text box content updates the bound property, and changes to the bound property update the text box content. Two-way binding isn’t necessary for this example, but it will be useful as we expand this example in the future.

For the text block, {x:Bind Task.Name, Mode=OneWay} means we want to bind the value shown in the text block to Task.Name. Since text blocks are read-only, two-way binding is not required in this case.

Stepping Through the Data Binding Process

This example consists of four steps:

  1. Start the app.
  2. Type something in the text box.
  3. Exit the text box by pressing Tab or clicking elsewhere in the window.
  4. Observe the result in the text block.

There’s a lot going on under the covers during the data binding process, and understanding simple data binding is helpful when more complex scenarios need to be debugged. To see what’s happening at each step, I ran the example app in the debugger, and set a breakpoint at every location that looked interesting (i.e., at the top of every function or property). Here’s what I observed.

1. Start the app

  • As a comment in the blank app template explains, public App() in App.xaml.cs “is the logical equivalent of main() or WinMain().” That’s where the app starts. It moves on to OnLaunched in the same file.
  • The app’s main page code starts executing in the MainPage constructor. Since we put a line in there to initialize the task view model, that construction process starts, beginning with the NotificationBase<T> constructor.

class NotificationBase<T> contains a protected member called This (note the capitalization) of type T, which in this case is type Task (the Task model). Since we didn’t pass a parameter to the constructor, This is just initialized with a new Task instance.

  • Next, the TaskViewModel constructor executes, initializing its private Task instance. The View Model is allowed to refer to the Model, since its role is to mediate communication between the Model and the View.
  • Before MainPage displays for the first time, it needs to retrieve the initial value of the task name. That requires calling three getters.
  • Getter #1: The Task getter in MainPage returns a TaskViewModel instance.
  • Getter #2: The Name getter in TaskViewModel returns This.Name.
  • Getter #3: Since This is an instance of Task, the third getter is the Name getter in the Task class.

2. Type something in the text box

3. Exit the text box by pressing Tab or clicking elsewhere in the window

At this point in the execution, MainPage is visible, and we can start typing in the text box. No binding code executes while we’re typing (since the binding system isn’t fast enough to bind continuously), but once the text box loses focus, a few things happen:

  • The Task getter in MainPage returns the TaskViewModel instance again.
  • Since the view model’s Name field is bound to the text box, the Name setter in TaskViewModel executes the following code to update Name:

    set { SetProperty(This.Name, value, () => This.Name = value); }

Unlike a simple setter that just updates a local variable, this setter delegates the assignment logic to another method, the SetProperty method in the NotificationBase class. It passes these parameters:

  • This.Name is Task.Name, the current value of the Task model’s string property.
  • value is the value that the user typed in the text box. As with all setters, the .NET Framework provides it in this built-in variable.
  • () => This.Name = value is a lambda expression, a function that is passed as a parameter. () means this function has no input parameters. => is the lambda operator, indicating that this is a lambda expression. This.Name = value is the lambda body, the body of the function. This purpose of this function is to update the model’s Name property to the value that the user has typed.

The SetProperty<T> method in NotificationBase has four parameters, though only three need to be passed:

  • T currentValue is the current value of the property to be set. T is string in this case, since we’re updating a string property.
  • T newValue is the new property value that we want to set.
  • Action doSet is the function that will update the model property. Action is a .NET type that allows a function to be passed as a parameter (or assigned to a variable).
  • [CallerMemberName] string property = null, the fourth parameter, doesn’t have to be passed explicitly. It uses a handy feature that tells the compiler to look up the name of the field that we’re giving a new value to. This saves the developer from having to keep this value up to date, since we need the correct field name in this function.

SetProperty has four steps:

  • if (EqualityComparer<T>.Default.Equals(currentValue, newValue)) return; exits the function if the current and new values are equal. We don’t want to run unnecessary binding code if there’s nothing to update.
  • doSet.Invoke() executes the function that we passed as a parameter, which updates the Task model’s string property with the new value.
  • RaisePropertyChanged(property) raises an event, which is handled by RaisePropertyChanged , a private method in NotificationBase. The purpose of the event is to notify binding targets that the bound value has changed.
  • RaisePropertyChanged has a single line of code:

    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property))

The ?. is a null-conditional operator, which provides a concise way to only call PropertyChanged if it is not null. The PropertyChanged method itself is in a file called MainPage.g.cs that is generated by the compiler. One of the advantages of using {x:Bind} is that you can step into this generated code with the debugger, to see exactly what’s going on. But for now, I won’t get into any more detail about code in MainPage.g.cs or the other generated source files. The important part is that it accomplishes the goal of sending a notification about the changed value.

4. Observe the result in the text block

The last step in the binding process is for the binding target to read the new value. The MainPage text block is bound to Task.Name, the same property on TaskViewModel that was updated in the previous step. A consequence of the PropertyChanged event firing is that the text block asks for the updated value by calling the TaskViewModel Name getter, which gets the actual value from the Task Name getter in the model.

There’s a lot more to MVVM and data binding, but this process of updating a single string value demonstrates the minimal file layout and execution process for the pattern to work. Next week, I’ll expand on the Model part of the pattern.

(Image credit: modified version of last week’s image)

замечания

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

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

Установка или настройка

Подробные инструкции по настройке или установке UWP.

Требования

  1. Windows 10
  2. Visual Studio 2015

меры

  • Загрузите и установите пользовательскую установку Visual Studio 2015, при этом убедитесь, что Universal Windows App Development Tools выбраны вместе со своими дополнительными параметрами:
    a) Инструменты и Windows SDK
    б) Эмулятор для Windows Phone

  • Обязательно включите режим разработки для разработки и развертывания устройства.

  • Выберите шаблон на основе языка, который вы хотите использовать:
    C # , Visual Basic , C ++ или JavaScript .

  • Затем создайте пустое приложение (Universal Windows).

  • Выберите целевую и минимальную версии Windows 10, подходящие для вашего приложения.

    Нажмите здесь, если вы не уверены, какие версии вы должны выбрать или просто оставите параметры по умолчанию и нажмите «ОК», чтобы начать работу!

моментальные снимки

Installation    

Проверенная опция UWP

Creating a new project

Расположение шаблона Blank App

Selecting Target and minimum version for your Application

Селектор минимальной и целевой версии

В этом примере демонстрируется, как разработать простое приложение UWP.

При создании проекта «Blank App (Universal Windows)» есть много важных файлов, созданных в вашем решении.

Все файлы в вашем проекте можно увидеть в обозревателе решений .

Некоторые из важных файлов в вашем проекте:

  • App.xaml и App.xaml.cs — App.xaml используется для объявления ресурсов, доступных в приложении, а App.xaml.cs — это код бэкэнд для него. App.xaml.cs является начальной точкой входа приложения
  • MainPage.xaml — это пользовательский интерфейс запуска по умолчанию для вашего приложения (вы также можете изменить стартовую страницу приложения в App.xaml.cs)
  • Package.appxmanifest — этот файл содержит важную информацию о вашем приложении, такую ​​как отображаемое имя, точка входа, визуальные активы, список возможностей, информация о упаковке и т. Д.

Начиная

  • Добавление кнопки на страницу

    Чтобы добавить элемент или инструмент UI на вашу страницу, просто перетащите элемент из окна панели инструментов слева. Найдите инструмент «Кнопка» на панели инструментов и отпустите его на странице своего приложения.

  • Настройка пользовательского интерфейса

    Все свойства для определенного инструмента отображаются в окне свойств на нижней стороне справа.

    Здесь мы изменим текст внутри кнопки «Говорить!». Для этого сначала нажмите на кнопку, чтобы выбрать ее, а затем прокрутите окно свойств, чтобы найти контент и изменить текст на нужную строку («Speak it!»).

    Мы также изменим цвет фона для страницы. Каждая страница имеет родительский элемент (обычно это сетка), который содержит все остальные элементы. Таким образом, мы изменим цвет родительской сетки. Для этого нажмите на сетку и измените кисть> Фон в окне свойств на нужный вам цвет.

Пользовательский интерфейс будет выглядеть примерно так, как только вы его настроили.

введите описание изображения здесь


  • Код позади

    Теперь давайте сделаем что-нибудь щелкнув по нашей кнопке!

    Нажатие на кнопку вызывает событие, и нам нужно обработать событие, чтобы сделать что-то полезное при нажатии кнопки.

    Добавление обработчика событий

    Чтобы добавить обработчик события клика к вашей кнопке, выберите кнопку, перейдите в окно свойств и выберите значок молнии . Это окно состоит из всех событий, которые доступны для выбранного элемента (кнопка в нашем случае). Затем дважды щелкните текстовое поле рядом с событием «Click», чтобы автоматически генерировать обработчик для события нажатия кнопки.

После этого вы будете перенаправлены на страницу ac # (MainPage.xaml.cs). Добавьте следующий код к методу обработчика событий:

 MediaElement mediaElement = new MediaElement();
        var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
        Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello, World!");
        mediaElement.SetSource(stream, stream.ContentType);
        mediaElement.Play();

Затем добавьте ключевое слово async в обработчик событий.

После добавления кода выше ваш класс должен выглядеть примерно так:

public sealed partial class MainPage : Page
{
    string speakIt = "Hello, World!";
    public MainPage()
    {
        this.InitializeComponent();
    }

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        MediaElement mediaElement = new MediaElement();
        var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
        Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(speakIt);
        mediaElement.SetSource(stream, stream.ContentType);
        mediaElement.Play();

    }
}
  • Запустите приложение!

    Ваше приложение готово к запуску. Вы можете запустить приложение, нажав F5 или выбрать свое устройство, на котором вы хотите развернуть и отладить ваше приложение, и нажать кнопку «Пуск».

введите описание изображения здесь

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

введите описание изображения здесь

  • Идти дальше

    Теперь, когда вы сделали свое первое приложение, давайте сделаем еще один шаг!

    Добавьте текстовое поле на свою страницу и нажав кнопку, приложение опубликует все, что написано в текстовом поле.

    Начните с перетаскивания элемента управления TextBox из панели инструментов в макет. Затем укажите имя своего TextBox в меню свойств. (почему нам нужно указывать имя? так что мы можем легко использовать этот элемент управления)

    Visual Studio по умолчанию дает вашему управлению имя, но это хорошая привычка называть элементы управления в соответствии с тем, что они делают или что-то важное.

    Я называю свой текстовый ящик — « speakText ».

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        //checking if the text provided in the textbox is null or whitespace
        if (!string.IsNullOrWhiteSpace(speakText.Text))
            speakIt = speakText.Text;
        else
            speakIt = "Please enter a valid string!";

        MediaElement mediaElement = new MediaElement();
        var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
        Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(speakIt);
        mediaElement.SetSource(stream, stream.ContentType);
        mediaElement.Play();

    }

Теперь разверните свой код!

Теперь ваше приложение может выдать любую допустимую строку, которую вы ему предоставляете!

stackoverflow - это потрясающе!

Поздравляем! Вы успешно создали свое собственное приложение UWP!

This section provides an overview of what uwp is, and why a developer might want to use it.

It should also mention any large subjects within uwp, and link out to the related topics. Since the Documentation for uwp is new, you may need to create initial versions of those related topics.

Creating your first UWP Application

This example demonstrates how to develop a simple UWP application.

On creation of a «Blank App (Universal Windows)» project there are many essential files that are created in your solution.

All files in your project can be seen in the Solution Explorer.

Some of the crucial files in your project are :

  • App.xaml and App.xaml.cs — App.xaml is used to declare resources that are available across the application and App.xaml.cs is the backend code for it. App.xaml.cs is the default entry point of the application
  • MainPage.xaml — This is the default startup UI page for your application (you can also change your application startup page in App.xaml.cs)
  • Package.appxmanifest — This file contains important information of your application like Display name,entry point,visual assets,list of capabilities,packaging information etc.

Getting started

  • Adding a button to your page

    To add any UI element or tool to your page simply drag and drop the element from the toolbox window on the left. Search for a «Button» tool in the toolbox and drop it in your app page.

  • Customizing the UI

    All properties for a particular tool is shown in the properties window on the Bottom Right side.

    Here we will change the text inside the button to «Speak it !». To do this first tap on the button to select it and then scroll through the properties window to find Content and change the text to your desired string («Speak it !»).

    We will also change the background colour for the page. Each page has a parent element (usually a grid) which contains all the other elements . Thus we will change the colour of the parent grid. To do this tap on the grid and change the Brush > Background from the properties window to your desired colour.

The UI will look something like this after you have customized it .

enter image description here


  • Code behind

    Now lets do something on click of our button!

    Clicking on a button triggers an event and we need to handle the event to do something useful when the button is clicked.

    Adding event handler

    To add a click event handler to your button , select the button go to the properties window and select the lightning bolt icon . This window consists of all the events that are available for the element that we selected (the button in our case). Next, double click on the textbox beside «Click» event to auto-generate the handler for the button click event.

After this you will be redirected to a c# page (MainPage.xaml.cs).
Add the following code to your event handler method:

 MediaElement mediaElement = new MediaElement();
        var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
        Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync("Hello, World!");
        mediaElement.SetSource(stream, stream.ContentType);
        mediaElement.Play();
 

Next, add async keyword to your event handler.

After adding the code above your class should look something like this:

public sealed partial class MainPage : Page
{
    string speakIt = "Hello, World!";
    public MainPage()
    {
        this.InitializeComponent();
    }

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        MediaElement mediaElement = new MediaElement();
        var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
        Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(speakIt);
        mediaElement.SetSource(stream, stream.ContentType);
        mediaElement.Play();

    }
}
 
  • Launch your app!

    Your application is ready to be launched. You can launch your application by pressing F5 or Select your device on which you want to deploy and debug your application and click on start button.

enter image description here

After getting built, your application will be deployed on to your device.
Depending on your device’s resolution and screen size the application will automatically configure its layout. ( You can resize the window to see how seamlessly it works)

enter image description here

  • Going further

    Now that you have made your first application, let’s go a step further !

    Add a textbox to your page and on click of the button, the app will speak out whatever is written in the textbox.

    Start by dragging and dropping a TextBox control from the Toolbox to your layout. Next, give a name to your TextBox from the properties menu. (why do we need to specify a name ? so that we can easily use this control)

    Visual Studio by default gives your control a name, but it’s a good habit to name controls according to what they do or something relevant.

    I am naming my textbox — «speakText«.

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        //checking if the text provided in the textbox is null or whitespace
        if (!string.IsNullOrWhiteSpace(speakText.Text))
            speakIt = speakText.Text;
        else
            speakIt = "Please enter a valid string!";

        MediaElement mediaElement = new MediaElement();
        var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
        Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(speakIt);
        mediaElement.SetSource(stream, stream.ContentType);
        mediaElement.Play();

    }
 

Now deploy your code!!

Your application is now able to speak out any valid string you provide to it !!

stackoverflow is awesome!

Congratulations ! You have successfully built your own UWP application !!

Installation or Setup

Detailed instructions on getting UWP set up or installed.

Requirements

  1. Windows 10
  2. Visual Studio 2015

Steps

  • Download and custom install Visual Studio 2015, while making sure that Universal Windows App Development Tools is selected along with its sub options:-
    a) Tools and Windows SDK
    b) Emulator for Windows Phone

  • Make sure to Enable Developer Mode on development and deploying device.

  • Select the template based on the language that you want to use:
    C#, Visual Basic, C++ or JavaScript.

  • Next create a Blank App (Universal Windows).

  • Select the Target and Minimum version of Windows 10 suitable for your application.

    Click here if you are not sure which versions you should choose or simply leave the options at their default values and click ‘OK’ to get started!

Snapshots

Installation    
 

Checked UWP Option

Creating a new project
 

Blank App Template Location

Selecting Target and minimum version for your Application
 

Minimum and Target Version selector

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Не является приложением win32 windows server
  • Как открыть доступ к application data в windows 7
  • Sfsync03 sys windows 10
  • Как получить директорию windows
  • Программа для отключения центра обновлений windows 10