Wpf для windows 10

Руководство: Модернизация приложения WPF Tutorial: Modernize a WPF app

Существует множество способов модернизировать имеющиеся классические приложения путем интеграции новейших функций Windows в существующий исходный код, вместо того чтобы создавать эти приложения с нуля. There are many ways to modernize existing desktop apps by integrating the latest Windows features into the existing source code instead of rewriting the apps from scratch. В этом руководстве мы рассмотрим несколько способов модернизации существующих бизнес-приложений WPF с помощью следующих компонентов: In this tutorial we’ll explore several ways to modernize an existing WPF line-of-business app by using these features:

  • .NET Core 3 .NET Core 3
  • элементы управления XAML платформы UWP с XAML Islands; UWP XAML controls with XAML Islands
  • адаптивные карточки и уведомления Windows 10. Adaptive Cards and Windows 10 notifications
  • Развертывание MSIX MSIX deployment

Для работы с этим руководством нужны следующие навыки разработки: This tutorial requires the following development skills:

  • опыт создания классических приложений для Windows на основе WPF; Experience in developing Windows desktop apps with WPF.
  • базовые навыки разработки на C# и XAML; Basic knowledge of C# and XAML.
  • базовое навыки работы с UWP. Basic knowledge of UWP.

Обзор Overview

В этом руководстве представлен код для простого бизнес-приложения WPF с именем Contoso Expenses. This tutorial provides the code for a simple WPF line-of-business app named Contoso Expenses. В нашем вымышленном сценарии для этого руководства менеджеры компании Contoso Corporation используют внутреннее приложение Contoso Expenses, чтобы отслеживать включенные в отчет расходы. In the fictional scenario of the tutorial, Contoso Expenses is an internal app used by managers of Contoso Corporation to keep track of the expenses submitted by their reports. Менеджеры получили в свое распоряжение сенсорные устройства, и теперь им нужно использовать приложение Contoso Expenses без мыши и клавиатуры. The managers are now equipped with touch-enabled devices, and they would like to use the Contoso Expenses app without a mouse or keyboard. К сожалению, текущая версия приложения не поддерживает сенсорный ввод. Unfortunately, the current version of the app isn’t touch friendly.

Компания Contoso решила модернизировать это приложение, добавив новые функции Windows для более эффективного создания отчетов о расходах. Contoso wants to modernize this app with new Windows features to enable employees to create expenses reports more efficiently. Многие из этих функций можно легко реализовать в новом приложении UWP. Many of the features could be easily implemented by building a new UWP app. Но существующее приложение очень сложное и является результатом многих лет работы нескольких команд. However, the existing app is complex and is the result of many years of development by different teams. Поэтому вариант переделки с нуля под новые технологии даже не рассматривается. As such, rewriting it from scratch with a new technology isn’t an option. Команда ищет оптимальный подход к добавлению новых возможностей в существующую базу кода. The team is looking for the best approach to add new features into the existing codebase.

На момент, соответствующий началу этого руководства, Contoso Expenses нацелено на платформу .NET Framework версии 4.7.2 и использует следующие сторонние библиотеки: At the beginning of the tutorial, Contoso Expenses targets the .NET Framework 4.7.2 and uses the following 3rd party libraries:

  • MVVM Light — базовая реализация шаблона MVVM; MVVM Light, a basic implementation for the MVVM pattern.
  • Unity — контейнер внедрения зависимостей; Unity, a dependency injection container.
  • LiteDb — встроенное решение NoSQL для хранения данных; LiteDb, an embedded NoSQL solution to store the data.
  • Bogus — инструмент для создания фиктивных данных. Bogus, a tool to generate fake data.

В этом руководстве объясняется, как улучшить приложение Contoso Expenses, дополнив его новыми функциями Windows. In the tutorial, you’ll enhance Contoso Expenses with new Windows features:

  • Миграция существующего приложения WPF на .NET Core 3.0. Migrate an existing WPF app to .NET Core 3.0. Это откроет вам новые и важные возможности на дальнейшую перспективу. This will open up new and important scenarios in the future.
  • Применение XAML Islands для размещения заключенных в оболочку элементов управления InkCanvas и MapControl, которые входят в набор инструментов сообщества Windows. Use XAML Islands to host the InkCanvas and MapControl wrapped controls provided by the Windows Community Toolkit.
  • Применение XAML Islands для размещения всех стандартных элементов управления XAML UWP (в нашем примере это CalendardView). Use XAML Islands to host any standard UWP XAML control (in this case, a CalendardView).
  • Интеграция адаптивных карточек и уведомлений Windows 10 в приложение. Integrate Adaptive Cards and Windows 10 notifications into the app.
  • Упаковка приложения с помощью MSIX и настройка конвейера CI/CD в Azure DevOps, который позволит автоматически предоставлять тест-инженерам и пользователям новые версии приложения по мере их появления. Package the app with MSIX and set up a CI/CD pipeline on Azure DevOps so that you can automatically deliver new versions of the app to testers and users as soon as it is available.
Читайте также:  Как правильно произносится linux

Предварительные условия Prerequisites

Для работы с этим руководством на компьютере разработки должны быть установлены следующие компоненты: To perform this tutorial, your development computer must have these prerequisites installed:

  • Windows 10, версия 1903 (сборка 18362) или более поздняя; Windows 10, version 1903 (build 18362) or a later version.
  • Visual Studio 2019; Visual Studio 2019.
  • пакет SDK для .NET Core 3 (установите последнюю версию). .NET Core 3 SDK (install the latest version).

Обеспечьте наличие следующих рабочих нагрузок и дополнительных компонентов Visual Studio 2019. Make sure you install the following workloads and optional features with Visual Studio 2019:

  • «Разработка классических приложений .NET». .NET Desktop development
  • «Разработка приложений для универсальной платформы Windows». Universal Windows Platform development
  • Пакет SDK для Windows 10 (версии 10.0.18362.0 и выше). Windows 10 SDK (10.0.18362.0 or later)

Получение примера приложения Contoso Expenses Get the Contoso Expenses sample app

Перед началом работы с этим руководством скачайте исходный код приложения Contoso Expenses и убедитесь, что этот код успешно компилируется в Visual Studio. Before you begin the tutorial, download the source code for the Contoso Expenses app and make sure you can build the code in Visual Studio.

  1. Исходный код приложения можно скачать на вкладке Releases (Выпуски) в репозитории AppConsult-WinAppsModernizationWorkshop. Download the app source code from the Releases tab of the AppConsult WinAppsModernization workshop repository. Вот прямая ссылка: https://github.com/microsoft/AppConsult-WinAppsModernizationWorkshop/releases. The direct link is https://github.com/microsoft/AppConsult-WinAppsModernizationWorkshop/releases.
  2. Откройте ZIP-файл и извлеките все его содержимое в корневую папку диска C:\ . Open the zip file and extract all the content to the root of your C:\ drive. В результате создастся папка C:\WinAppsModernizationWorkshop. It will create a folder named C:\WinAppsModernizationWorkshop.
  3. Откройте Visual Studio 2019 и дважды щелкните файл C:\WinAppsModernizationWorkshop\Lab\Exercise1\01-Start\ContosoExpenses\ContosoExpenses.sln, чтобы открыть это решение. Open Visual Studio 2019 and double click on the C:\WinAppsModernizationWorkshop\Lab\Exercise1\01-Start\ContosoExpenses\ContosoExpenses.sln file to open the solution.
  4. Убедитесь, что проект WPF для Contoso Expenses успешно компилируется, запускается и отлаживается по нажатию кнопки Запуск или клавиш CTRL+F5. Verify that you can build, run, and debug the Contoso Expenses WPF project by pressing the Start button or CTRL + F5.

Приступая к работе Get started

Получив исходный код для примера приложения Contoso Expenses и убедившись, что он компилируется в Visual Studio, переходите к работе с нашим руководством: After you have the source code for the Contoso Expenses sample app and you can confirm that you can build it in Visual Studio, you’re ready to start the tutorial:

Важные понятия Important concepts

Следующие разделы содержат общие сведения о некоторых важных понятиях, обсуждаемых в этом руководстве. The following sections provide background for some of the key concepts discussed in this tutorial. Если вы уже знакомы с этими понятиями, можете пропустить этот раздел. If you’re already familiar with these concepts, you can skip this section.

Читайте также:  Dell g5 5590 linux

Универсальная платформа Windows (UWP) Universal Windows Platform (UWP)

В ОС Windows 8 корпорация Майкрософт представила новую платформу — среда выполнения Windows (WinRT). In Windows 8, Microsoft introduced a new framework called the Windows Runtime (WinRT). В отличие от .NET Framework платформа WinRT реализована как собственный уровень интерфейсов API, напрямую предоставляемых приложениям. Unlike the .NET Framework, WinRT is a native layer of APIs which are exposed directly to apps. Также в WinRT реализованы языковые проекции, которые добавляются поверх среды выполнения и позволяют разработчикам взаимодействовать с ними не только на C++, но и на других языках, как например C# и JavaScript. WinRT also introduced language projections, which are layers added on top of the runtime to allow developers to interact with it using languages such as C# and JavaScript in addition to C++. Эти проекции позволяют разработчикам создавать приложения на основе WinRT, используя те же навыки работы с C# и XAML, которые они получили при создании приложений для .NET Framework. Projections enable developers to build apps on top of WinRT that leverage the same C# and XAML knowledge they acquired in building apps with the .NET Framework.

В ОС Windows 10 Корпорация Майкрософт представила созданную на основе WinRT универсальную платформу Windows (UWP). In Windows 10, Microsoft introduced the Universal Windows Platform (UWP), which is built on top of WinRT. Самой важной функцией UWP является то, что она предоставляет общий набор интерфейсов API для всех платформ устройств. Вы можете использовать одни и те же интерфейсы API в приложении на настольном компьютере, Xbox One или HoloLens. The most important feature of UWP is that it offers a common set of APIs across every device platform: no matter if the app is running on a desktop, on a Xbox One or on a HoloLens, you’re able to use the same APIs.

Теперь большинство новых функций Windows 10, в том числе временная шкала, Project Rome и Windows Hello, предоставляются через интерфейсы API WinRT. Going forward, most new Windows 10 features are exposed via WinRT APIs, including features such as Timeline, Project Rome, and Windows Hello.

Упаковка MSIX MSIX packaging

MSIX — современная модель упаковки для приложений Windows. MSIX is the modern packaging model for Windows apps. MSIX поддерживает приложения UWP и классические приложения, в которых используются технологии Win32, WPF, Windows Forms, Java, Electron и др. MSIX supports UWP apps as well as desktop apps building using technologies such as Win32, WPF, Windows Forms, Java, Electron, and more. Классическое приложение, упакованное в пакет MSIX, можно опубликовать в Microsoft Store. When you package a desktop app in an MSIX package, you can publish your app to the Microsoft Store. Также классическое приложение при установке получает идентификатор пакета, что позволяет классическому приложению использовать более широкий набор интерфейсов API WinRT. Your desktop app also get package identity when it is installed, which enables your desktop app to use a broader set of WinRT APIs.

Дополнительные сведения доступны в следующих статьях. For more information, see these articles:

XAML Islands XAML Islands

Начиная с Windows 10 версии 1903, вы можете размещать элементы управления универсальной платформы Windows (UWP) в классических приложениях, созданных не на платформе UWP, используя функцию XAML Island. Starting in Windows 10, version 1903, you can host UWP controls in non-UWP desktop apps using a feature called XAML Islands. Эта функция позволяет улучшить внешний вид и функциональность существующих классических приложений, дополнив их новейшими возможностями пользовательского интерфейса Windows 10, которые доступны только через элементы управления UWP. This feature enables you to enhance the look, feel, and functionality of your existing desktop apps with the latest Windows 10 UI features that are only available via UWP controls. Это позволяет применять в имеющихся приложениях WPF, Windows Forms и Win32 на C++ такие функции UWP, как Windows Ink, и элементы управления, которые поддерживают систему Fluent Design. This means that you can use UWP features such as Windows Ink and controls that support the Fluent Design System in your existing WPF, Windows Forms, and C++ Win32 apps.

Читайте также:  Как подключить rdp windows server 2012

Дополнительные сведения см. в статье Элементы управления UWP в классических приложениях (XAML Islands). For more information, see UWP controls in desktop applications (XAML Islands). В этом руководстве описаны процессы применения двух разных типов элементов управления XAML Islands. This tutorial guides you through the process of using two different types of XAML Island controls:

Это InkCanvas и MapControl из набора инструментов сообщества Windows. The InkCanvas and MapControl in the Windows Community Toolkit. Эти элементы управления WPF служат оболочкой для интерфейса и функциональных возможностей соответствующих элементов управления UWP, и их можно использовать в конструкторе Visual Studio, как любой другой элемент управления WPF. These WPF controls wrap the interface and functionality of the corresponding UWP controls and can be used like any other WPF control in the Visual Studio designer.

Элемент управления UWP Представление календаря. The UWP Calendar view control. Это стандартный элемент управления UWP, для размещения которого применяется WindowsXamlHost из набора инструментов сообщества Windows. This is a standard UWP control that you will host by using the WindowsXamlHost control in the Windows Community Toolkit.

.NET Core 3 .NET Core 3

Платформа с открытым исходным кодом .NET Core реализует кроссплатформенную, простую и расширяемую версию полной .NET Framework. .NET Core is an open-source framework that implements a cross-platform, lightweight and easily extensible version of the full .NET Framework. По сравнению с полной платформой .NET Framework, .NET Core запускается намного быстрее и в ней оптимизированы многие из интерфейсов API. Compared to the full .NET Framework, .NET Core startup time is much faster and many of the APIs have been optimized.

В первых нескольких выпусках основное внимание в .NET Core уделялось поддержке веб-приложений и (или) приложений серверной части. Through its first several releases, the focus of .NET Core was for supporting web or back-end apps. С помощью .NET Core вы можете легко создавать масштабируемые веб-приложения или API, которые могут размещаться на Windows, Linux или в архитектурах микрослужб, таких как контейнеры Docker. With .NET Core, you can easily build scalable web apps or APIs that can be hosted on Windows, Linux, or in micro-service architectures like Docker containers.

Последний выпуск .NET Core — .NET Core 3. .NET Core 3 is latest release of .NET Core. Основным преимуществом этого выпуска является поддержка классических приложений для Windows, включая приложения Windows Forms и WPF. The highlight of this release is support for Windows desktop apps, including Windows Forms and WPF apps. Используя .NET Core 3, вы можете запускать новые и существующие классические приложения для Windows и пользоваться всеми преимуществами этой платформы. You can run new and existing Windows desktop apps on .NET Core 3 and enjoy all the benefits that .NET Core has to offer. В приложениях для Windows Forms и WPF, предназначенных для .NET Core 3, вы сможете использовать элементы управления UWP, доступные в XAML Islands. UWP controls that are hosted in XAML Islands can also be used in Windows Forms and WPF apps that target .NET Core 3.

WPF и Windows Forms не будут кроссплатформенными, то есть вы не сможете запускать WPF или Windows Forms в Linux или MacOS. WPF and Windows Forms are not becoming cross-platform, and you cannot run a WPF or Windows Forms on Linux and MacOS. Компоненты пользовательского интерфейса WPF и Windows Forms по-прежнему зависят от системы визуализации Windows. The UI components of WPF and Windows Forms still have a dependency on the Windows rendering system.

Дополнительные сведения см. в статье Новые возможности .NET Core 3.0. For more information, see What’s new in .NET Core 3.0.

Оцените статью