Windows application in wpf

Содержание
  1. Open WPF window in WindowsForm APP [duplicate]
  2. 3 Answers 3
  3. Разработка приложений Application Development
  4. Управление приложениями Application Management
  5. Ресурсы, Содержимое и Файлы данных WPF-приложения WPF Application Resource, Content, and Data Files
  6. Окна и диалоговые окна Windows and Dialog Boxes
  7. Навигация Navigation
  8. Hosting Hosting
  9. Построение и Развертывание Build and Deploy
  10. Учебник. Создание простого приложения на C# Tutorial: Create a simple application with C#
  11. Предварительные требования Prerequisites
  12. Настройка интегрированной среды разработки (IDE) Configure the IDE
  13. Создание проекта Create the project
  14. Изменение имени MainWindow.xaml Change the name of MainWindow.xaml
  15. Конструирование пользовательского интерфейса (ИП) Design the user interface (UI)
  16. Добавление элемента управления TextBlock Add a TextBlock control
  17. Настройка текста в текстовом блоке Customize the text in the text block
  18. Добавление переключателей Add radio buttons
  19. Добавление отображаемого текста для каждого переключателя Add display text for each radio button
  20. Задание переключателя, выбранного по умолчанию Set a radio button to be checked by default
  21. Добавление элемента управления Button Add the button control
  22. Добавление кода к кнопке Display Add code to the display button
  23. Отладка и тестирование приложения Debug and test the application
  24. Поиск и исправление ошибок Find and fix errors
  25. Начало отладки и поиск ошибки Start debugging and find the error
  26. Задание Greetings.xaml в качестве начального универсального кода ресурса (URI) Specify Greetings.xaml as the startup URI
  27. Отладка с точками останова Debug with breakpoints
  28. Добавление точек останова Add breakpoints
  29. Просмотр представления элементов пользовательского интерфейса View a representation of the UI elements
  30. Сборка окончательной версии приложения Build a release version of the application
  31. Следующие шаги Next steps

Open WPF window in WindowsForm APP [duplicate]

I added to my WindowsForm app a new WPF window called novoLogin.

After adding it, I added the system.xaml reference. debug fine.

Now I’m trying to open this new window from the existing windowsForm.

The compiler is giving this error:

Error 1 ‘WindowsFormsApplication1.novoLogin’ does not contain a definition for ‘show’ and no extension method ‘show’ accepting a first argument of type ‘WindowsFormsApplication1.novoLogin’ could be found (are you missing a using directive or an assembly reference?)

3 Answers 3

This brief article explains how you can achieve this.

If you find yourself in need to open a WPF Window from a WinForms program, this is one way to do it (works for me):

  1. Create/Add a new project of type WPF Custom Control Library
  2. Add a new Item of type Window (WPF)
  3. Do your thing with the WPF Window

From your WinForms app, create and open the WPF Window

Open the project’s manifest file (the one with the .csproj or .vbproj extension) in any text editor. The top node usually contains several tags, one for each build configuration and a global one. In the global node (the one without Condition attribute), search for the sub-node or create one if it does not exist. This node should contain two GUIDs: FAE04EC0-301F-11D3-BF4B-00C04F79EFBC, which stands for a C# project, and 60dc8134-eba5-43b8-bcc9-bb4bc16c2548 which stands for WPF. The full line should look as follows:

(If you’re interested in details, codeproject holds a complete list of potential project GUIDs: http://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs)

Reload the project in Visual Studio, and open the Add New Item wizard.

Since the project is now officially classified as WPF project, this wizard should now contain the WPF window option. By the way, since there is no WinForms project GUID that could be overwritten, this approach does not harm the existing project components.

Разработка приложений Application Development

Windows Presentation Foundation (WPF) — это платформа представления, с помощью которой можно разрабатывать приложения следующих типов: Windows Presentation Foundation (WPF) is a presentation framework that can be used to develop the following types of applications:

автономные приложения (традиционные Windows-приложения, созданные как исполняемые сборки, которые устанавливаются и запускаются с клиентского компьютера); Standalone Applications (traditional style Windows applications built as executable assemblies that are installed to and run from the client computer).

XAML-приложения браузера (XBAP) (приложения, состоящие из страниц навигации, созданные как исполняемые сборки, которые размещаются в веб-браузерах, таких как Microsoft Internet Explorer и Mozilla Firefox); XAML browser applications (XBAPs) (applications composed of navigation pages that are built as executable assemblies and hosted by Web browsers such as Microsoft Internet Explorer or Mozilla Firefox).

пользовательские библиотеки элементов управления (неисполняемые сборки, содержащие многократно используемые элементы управления); Custom Control Libraries (non-executable assemblies containing reusable controls).

библиотеки классов (неисполняемые сборки, содержащие многократно используемые классы). Class Libraries (non-executable assemblies that contain reusable classes).

Использование типов WPF в службе Windows настоятельно не рекомендуется. Using WPF types in a Windows service is strongly discouraged. При попытке использовать эти возможности в службе Windows они могут не работать должным образом. If you attempt to use these features in a Windows service, they may not work as expected.

Для создания этого набора приложений WPF реализует множество служб. To build this set of applications, WPF implements a host of services. Этот раздел предоставляет обзор этих служб и место, где искать дополнительные сведения. This topic provides an overview of these services and where to find more information.

Управление приложениями Application Management

Исполняемым приложениям WPF часто требуется основной набор функциональных возможностей, включающий следующее: Executable WPF applications commonly require a core set of functionality that includes the following:

создание и управление общей инфраструктурой приложений (включая создание метода точки входа и цикл обработки сообщений Windows для получения системных и входящих сообщений); Creating and managing common application infrastructure (including creating an entry point method and a Windows message loop to receive system and input messages).

отслеживание и взаимодействие со временем существования приложения; Tracking and interacting with the lifetime of an application.

извлечение и обработка параметров командной строки; Retrieving and processing command-line parameters.

совместное использование свойств области приложения и ресурсов UI UI ; Sharing application-scope properties and UI UI resources.

обнаружение и обработка необработанных исключений; Detecting and processing unhandled exceptions.

возврат кодов завершения; Returning exit codes.

управление окнами в автономных приложениях; Managing windows in standalone applications.

отслеживание переходов в XAML-приложениях браузера (XBAP) и автономных приложениях с окнами навигации и фреймами. Tracking navigation in XAML browser applications (XBAPs), and standalone applications with navigation windows and frames.

Эти возможности реализуются с помощью класса Application, который добавляется в приложения с помощью определения приложения. These capabilities are implemented by the Application class, which you add to your applications using an application definition.

Ресурсы, Содержимое и Файлы данных WPF-приложения WPF Application Resource, Content, and Data Files

WPF расширяет базовую поддержку внедренных ресурсов в Microsoft .NET Framework, обеспечивая поддержку трех типов неисполняемых файлов данных: ресурсов, содержимого и данных. WPF extends the core support in the Microsoft .NET Framework for embedded resources with support for three kinds of non-executable data files: resource, content, and data. Дополнительные сведения см. в разделе Файлы ресурсов, содержимого и данных WPF-приложения. For more information, see WPF Application Resource, Content, and Data Files.

Ключевым компонентом поддержки неисполняемых файлов данных WPF является возможность их идентификации и загрузки с помощью уникального универсального кода ресурса (URI). A key component of the support for WPF non-executable data files is the ability to identify and load them using a unique URI. Дополнительные сведения см. в разделе URI типа «pack» в WPF. For more information, see Pack URIs in WPF.

Окна и диалоговые окна Windows and Dialog Boxes

Пользователи взаимодействуют с автономными приложениями WPF посредством окон. Users interact with WPF standalone applications through windows. Предназначением окна является размещение содержимого приложения и предоставление функциональных возможностей приложения, которые обычно позволяют пользователям взаимодействовать с содержимым. The purpose of a window is to host application content and expose application functionality that usually allows users to interact with the content. В WPF окна находятся в классе Window, который поддерживает следующие возможности: In WPF, windows are encapsulated by the Window class, which supports:

создание и отображение окон; Creating and showing windows.

установка отношений владельца/собственного окна; Establishing owner/owned window relationships.

настройка внешнего вида окна (например, размер, расположение, значки, текст заголовка, границы); Configuring window appearance (for example, size, location, icons, title bar text, border).

отслеживание и взаимодействие со временем существования окна. Tracking and interacting with the lifetime of a window.

Дополнительные сведения см. в разделе Общие сведения об окнах WPF. For more information, see WPF Windows Overview.

Window поддерживает возможность создать особый тип окна, известный как диалоговое окно. Window supports the ability to create a special type of window known as a dialog box. Можно создавать модальные и немодальные типы диалоговых окон. Both modal and modeless types of dialog boxes can be created.

Для удобства работы, обеспечения преимуществ повторного использования кода и согласованности пользовательского интерфейса в разных приложениях WPF предоставляет три стандартных диалоговых окна Windows: OpenFileDialog, SaveFileDialog и PrintDialog. For convenience, and the benefits of reusability and a consistent user experience across applications, WPF exposes three of the common Windows dialog boxes: OpenFileDialog, SaveFileDialog, and PrintDialog.

Окно сообщения представляет собой особый тип диалогового окна для отображения важной текстовой информации для пользователей и задания простых вопросов (да, нет, ОК, отмена). A message box is a special type of dialog box for showing important textual information to users, and for asking simple Yes/No/OK/Cancel questions. Класс MessageBox используется для создания и отображения окон сообщений. You use the MessageBox class to create and show message boxes.

Дополнительные сведения см. в разделе Общие сведения о диалоговых окнах. For more information, see Dialog Boxes Overview.

WPF поддерживает навигацию в интернет-стиле с использованием страниц (Page) и гиперссылок (Hyperlink). WPF supports Web-style navigation using pages (Page) and hyperlinks (Hyperlink). Навигация может быть реализована разнообразными способами, включая следующие: Navigation can be implemented in a variety of ways that include the following:

автономные страницы, размещенные в веб-браузере; Standalone pages that are hosted in a Web browser.

страницы, скомпилированные в приложение XBAP, которое размещается в веб-браузере; Pages compiled into an XBAP that is hosted in a Web browser.

страницы, скомпилированные в автономном приложении и размещенные в окне навигации (NavigationWindow); Pages compiled into a standalone application and hosted by a navigation window (NavigationWindow).

страницы, размещенные во фрейме (Frame), который может располагаться на отдельной странице или на странице, скомпилированной в приложение XBAP или в автономное приложение. Pages that are hosted by a frame (Frame), which may be hosted in a standalone page, or a page compiled into either an XBAP or a standalone application.

Для упрощения навигации WPF реализует следующее: To facilitate navigation, WPF implements the following:

совместно используемый механизм навигации NavigationService для обработки запросов навигации, который используют Frame, NavigationWindow и приложения XBAP для поддержки навигации внутри приложения; NavigationService, the shared navigation engine for processing navigation requests that is used by Frame, NavigationWindow, and XBAPs to support intra-application navigation.

методы навигации для инициирования навигации; Navigation methods to initiate navigation.

события переходов для отслеживания и взаимодействия со временем существования перехода; Navigation events to track and interact with navigation lifetime.

запоминание переходов назад и вперед с использованием журнала, который может быть проверен и обработан. Remembering back and forward navigation using a journal, which can also be inspected and manipulated.

WPF также поддерживает особый тип навигации — структурированную навигацию. WPF also supports a special type of navigation known as structured navigation. Структурированная навигация может использоваться для вызова одной или нескольких страниц, которые возвращают данные структурированным и предсказуемым способом, согласованным с вызывающими функциями. Structured navigation can be used to call one or more pages that return data in a structured and predictable way that is consistent with calling functions. Эта возможность зависит от класса PageFunction , который описан далее в разделе Общие сведения о структурной навигации. This capability depends on the PageFunction class, which is described further in Structured Navigation Overview. PageFunction также позволяет упростить создание сложных топологий переходов, которые описаны в разделе Общие сведения о топологии переходов. PageFunction also serves to simplify the creation of complex navigation topologies, which are described in Navigation Topologies Overview.

Hosting Hosting

Приложения XBAP могут размещаться в Microsoft Internet Explorer или Firefox. XBAPs can be hosted in Microsoft Internet Explorer or Firefox. Каждая модель размещения имеет свой собственный набор разрешений и ограничений, которые рассматриваются в разделе Размещение. Each hosting model has its own set of considerations and constraints that are covered in Hosting.

Построение и Развертывание Build and Deploy

Хотя простые приложения WPF могут быть собраны из командной строки с помощью компиляторов командной строки, WPF интегрируется с Visual Studio для обеспечения дополнительной поддержки, которая упрощает процесс разработки и сборки. Although simple WPF applications can be built from a command prompt using command-line compilers, WPF integrates with Visual Studio to provide additional support that simplified the development and build process. Дополнительные сведения см. в разделе Построение приложения WPF. For more information, see Building a WPF Application.

В зависимости от типа приложения вы можете выбрать один или несколько параметров развертывания. Depending on the type of application you build, there are one or more deployment options to choose from. Дополнительные сведения см. в разделе Развертывание приложений WPF. For more information, see Deploying a WPF Application.

Учебник. Создание простого приложения на C# Tutorial: Create a simple application with C#

При изучении этого руководства вы ознакомитесь со многими инструментами, диалоговыми окнами и конструкторами, которые можно использовать для разработки приложений в Visual Studio. By completing this tutorial, you’ll become familiar with many of the tools, dialog boxes, and designers that you can use when you develop applications with Visual Studio. Вам предстоит создать простое приложение «Hello, World», разработать пользовательский интерфейс, добавить код и выполнить отладку, одновременно приобретая навыки работы в интегрированной среде разработки (IDE). You’ll create a «Hello, World» application, design the UI, add code, and debug errors, while you learn about working in the integrated development environment (IDE).

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

Установите Visual Studio бесплатно со страницы скачиваемых материалов Visual Studio, если еще не сделали этого. If you haven’t already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

  • Установите Visual Studio бесплатно со страницы скачиваемых материалов Visual Studio, если еще не сделали этого. If you haven’t already installed Visual Studio, go to the Visual Studio downloads page to install it for free.
  • Для работы с этим руководством можно использовать либо .NET Framework, либо .NET Core. You can use either .NET Framework or .NET Core for this tutorial. .NET Core — это более новая, современная платформа. .NET Core is the newer, more modern framework. Для использования .NET Core требуется Visual Studio 2019 версии 16.3 или более поздней. .NET Core requires Visual Studio 2019 version 16.3 or later.

Настройка интегрированной среды разработки (IDE) Configure the IDE

При первом открытии Visual Studio вам будет предложено выполнить вход. When you open Visual Studio for the first time, you’ll be prompted to sign in. Для целей этого руководства это необязательно. This step is optional for this tutorial. Затем может появиться диалоговое окно, в котором предлагается выбрать параметры разработки и цветовую тему. Next you may be shown a dialog box that asks you to choose your development settings and color theme. Оставьте значения по умолчанию и нажмите Запуск Visual Studio. Keep the defaults and choose Start Visual Studio.

После запуска Visual Studio вы увидите окна инструментов, меню и панели инструментов, а также основную область окна. After Visual Studio launches, you’ll see tool windows, the menus and toolbars, and the main window space. Окна инструментов закреплены в левой и правой частях окна приложения, а панель Быстрый запуск, строка меню и стандартная панель инструментов закреплены в верхней его части. Tool windows are docked on the left and right sides of the application window, with Quick Launch, the menu bar, and the standard toolbar at the top. В центре окна приложения находится Начальная страница. In the center of the application window is the Start Page. При загрузке решения или проекта редакторы и конструкторы отображаются в области Начальной страницы . When you load a solution or project, editors and designers appear in the space where the Start Page is. При разработке приложения чаще всего используется именно эта область. When you develop an application, you’ll spend most of your time in this central area.

![Visual Studio 2017. Интегрированная среда разработки, в которой установлены общие параметры](../media/exploreide-idewithgeneralsettings.png «Снимок экрана: Visual Studio 2017. Интегрированная среда разработки, в которой установлены общие параметры»)

При запуске Visual Studio сначала открывается начальное окно. When you launch Visual Studio, the start window opens first. Выберите Продолжить без кода, чтобы открыть среду разработки. Select Continue without code to open the development environment. Вы увидите окна инструментов, меню и панели инструментов, а также основную область окна. You’ll see tool windows, the menus and toolbars, and the main window space. Окна инструментов закреплены в левой и правой частях окна приложения, а поле поиска, строка меню и стандартная панель инструментов закреплены в верхней его части. Tool windows are docked on the left and right sides of the application window, with a search box, the menu bar, and the standard toolbar at the top. При загрузке решения или проекта редакторы и конструкторы отображаются в центральной области окна приложения. When you load a solution or project, editors and designers appear in the central space of the application window. При разработке приложения чаще всего используется именно эта область. When you develop an application, you’ll spend most of your time in this central area.

Создание проекта Create the project

При создании приложения в Visual Studio необходимо сначала создать проект и решение. When you create an application in Visual Studio, you first create a project and a solution. Этот пример демонстрирует создание проекта Windows Presentation Foundation (WPF). For this example, you’ll create a Windows Presentation Foundation (WPF) project.

Создайте новый проект. Create a new project. В строке меню выберите Файл > Новый > Проект. On the menu bar, select File > New > Project.

В диалоговом окне Новый проект выберите категорию Установленные > Visual C# > Рабочий стол Windows, а затем выберите шаблон Приложения WPF (.NET Framework). In the New Project dialog, select the Installed > Visual C# > Windows Desktop category, and then select the WPF App (.NET Framework) template. Присвойте проекту имя HelloWPFApp и щелкните ОК. Name the project HelloWPFApp, and select OK.

Запустите Visual Studio 2019. Open Visual Studio 2019.

На начальном экране выберите Создать проект. On the start window, choose Create new project.

На экране Создание проекта выполните поиск по запросу «WPF», выберите в результатах Приложение WPF и нажмите кнопку Далее. On the Create a new project screen, search for «WPF,» choose WPF Application, and then choose Next.

На следующем экране присвойте проекту имя HelloWPFApp и щелкните Далее. At the next screen, give the project a name, HelloWPFApp, and choose Next.

В окне Дополнительные сведения для целевой платформы должна быть указана версия .NET Core 3.1. In the Additional information window, .NET Core 3.1 should already be selected for your target framework. Если это не так, выберите .NET Core 3.1. If not, select .NET Core 3.1. Затем нажмите Создать. Then, choose Create.

Visual Studio создает решение и проект HelloWPFApp, а в обозревателе решений выводятся различные файлы. Visual Studio creates the HelloWPFApp project and solution, and Solution Explorer shows the various files. Конструктор WPF отображает представление кода и представление XAML MainWindow.xaml в представлении с разделением. The WPF Designer shows a design view and a XAML view of MainWindow.xaml in a split view. Сдвигая разделитель, можно делать любое из представлений больше или меньше. You can slide the splitter to show more or less of either view. Можно выбрать для просмотра только визуальное представление или только представление XAML. You can choose to see only the visual view or only the XAML view.

Дополнительные сведения о XAML (eXtensible Application Markup Language) см. в обзоре XAML для WPF. For more information about XAML (eXtensible Application Markup Language), see the XAML overview for WPF page.

После создания проекта его можно настраивать. After you create the project, you can customize it. Для этого выберите Окно свойств в меню Представление или нажмите клавишу F4. To do so, choose Properties Window from the View menu, or press F4. Затем можно отображать и изменять параметры элементов проекта, элементов управления и других элементов в приложении. Then, you can display and change options for project items, controls, and other items in an application.

Изменение имени MainWindow.xaml Change the name of MainWindow.xaml

Давайте присвоим файлу MainWindow более конкретное имя. Let’s give MainWindow a more specific name. В обозревателе решений щелкните правой кнопкой мыши файл MainWindow.xaml и выберите команду Переименовать. In Solution Explorer, right-click on MainWindow.xaml and choose Rename. Измените имя файла на Greetings.xaml. Rename the file to Greetings.xaml.

Конструирование пользовательского интерфейса (ИП) Design the user interface (UI)

Если конструктор не открыт, выберите файл Greetings.xaml и нажмите клавиши SHIFT+F7, чтобы открыть его. If the designer is not open, select Greetings.xaml and press Shift+F7 to open the designer.

В приложение будут добавлены элементы управления трех типов: элемент управления TextBlock, два элемента управления RadioButton и элемент управления Button. We’ll add three types of controls to this application: a TextBlock control, two RadioButton controls, and a Button control.

Добавление элемента управления TextBlock Add a TextBlock control

Нажмите клавиши CTRL+Q для активации поля поиска и введите Панель элементов. Press Ctrl+Q to activate the search box and type Toolbox. Выберите в списке результатов Представление > Панель элементов. Choose View > Toolbox from the results list.

В окне Панель элементов разверните узел Типовые элементы управления WPF, чтобы увидеть элемент управления TextBlock. In the Toolbox, expand the Common WPF Controls node to see the TextBlock control.

Добавьте элемент управления TextBlock в область конструктора, выбрав элемент управления TextBlock и перетащив его в окно. Add a TextBlock control to the design surface by choosing the TextBlock item and dragging it to the window on the design surface. Отцентрируйте этот элемент в верхней части окна. Center the control near the top of the window. В Visual Studio 2019 и более поздних версиях для выравнивания элемента управления по центру можно использовать красные направляющие. In Visual Studio 2019 and later, you can use the red guidelines to center the control.

Окно должно выглядеть так, как показано на следующем рисунке: Your window should resemble the following illustration:

Разметка XAML должна выглядеть приблизительно так, как в следующем примере: The XAML markup should look something like the following example:

Настройка текста в текстовом блоке Customize the text in the text block

В представлении XAML найдите разметку для TextBlock и измените атрибут Text с TextBox на Select a message option and then choose the Display button. . In the XAML view, locate the markup for TextBlock and change the Text attribute from TextBox to Select a message option and then choose the Display button.

Разметка XAML должна выглядеть приблизительно так, как в следующем примере: The XAML markup should look something like the following example:

При необходимости снова разместите элемент TextBlock по центру и сохраните изменения сочетанием клавиш CTRL+S или с помощью пункта меню Файл. Center the TextBlock again if you like, and then save your changes by pressing Ctrl+S or using the File menu item.

Следующий шаг — добавить в форму два элемента управления RadioButton. Next, you’ll add two RadioButton controls to the form.

Добавление переключателей Add radio buttons

На панели элементов найдите элемент управления RadioButton. In the Toolbox, find the RadioButton control.

Добавьте два элемента управления RadioButton в область конструктора, выбрав элемент RadioButton и перетащив его в область конструктора. Add two RadioButton controls to the design surface by choosing the RadioButton item and dragging it to the window on the design surface. Переместите кнопки (выбрав их и используя клавиши со стрелками), чтобы кнопки отображались рядом под элементом управления TextBlock. Move the buttons (by selecting them and using the arrow keys) so that the buttons appear side by side under the TextBlock control. Используйте красные направляющие для выравнивания элемента управления. Use the red guidelines to align the controls.

Окно должно выглядеть следующим образом: Your window should look like this:

В окне Свойства для левого элемента управления RadioButton измените свойство Имя (свойство в верхней части окна Свойства ), задав ему значение HelloButton . In the Properties window for the left RadioButton control, change the Name property (the property at the top of the Properties window) to HelloButton .

В окне Свойства правого элемента управления RadioButton измените свойство Имя, задав ему значение GoodbyeButton , и затем сохраните изменения. In the Properties window for the right RadioButton control, change the Name property to GoodbyeButton , and then save your changes.

Теперь вы добавите отображаемый текст для каждого элемента управления RadioButton. Next, you’ll add display text for each RadioButton control. Следующая процедура обновляет свойство Content элемента управления RadioButton. The following procedure updates the Content property for a RadioButton control.

Добавление отображаемого текста для каждого переключателя Add display text for each radio button

Измените атрибут Content для кнопок HelloButton и GoodbyeButton на «Hello» и «Goodbye» в XAML. Update the Content attribute for the HelloButton and GoodbyeButton to «Hello» and «Goodbye» in the XAML. Разметка XAML теперь должна выглядеть следующим образом: The XAML markup should now look similar to the following example:

Задание переключателя, выбранного по умолчанию Set a radio button to be checked by default

На этом этапе мы настроим элемент HelloButton как выбранный по умолчанию, чтобы всегда был выбран один из переключателей. In this step, we’ll set HelloButton to be checked by default so that one of the two radio buttons is always selected.

В представлении XAML найдите разметку для элемента HelloButton. In the XAML view, locate the markup for HelloButton.

Добавьте атрибут IsChecked и задайте для него значение True. Add an IsChecked attribute and set it to True. В частности, добавьте IsChecked=»True» . Specifically, add IsChecked=»True» .

Разметка XAML теперь должна выглядеть следующим образом: The XAML markup should now look similar to the following example:

Последний элемент пользовательского интерфейса, который вам предстоит добавить, — это Button. The final UI element that you’ll add is a Button control.

Добавление элемента управления Button Add the button control

На панели элементов найдите элемент управления Button и добавьте его в область конструктора под элементами управления RadioButton, перетащив его на форму в представлении конструирования. In the Toolbox, find the Button control, and then add it to the design surface under the RadioButton controls by dragging it to the form in the design view. Если вы используете Visual Studio 2019 или более позднюю версию, выровнять элемент управления по центру можно с помощью красной линии. If you’re using Visual Studio 2019 or later, a red line helps you center the control.

В представлении XAML измените значение свойства Содержимое элемента управления Button с Content=»Button» на Content=»Display» и сохраните изменения. In the XAML view, change the value of Content for the Button control from Content=»Button» to Content=»Display» , and then save the changes.

Окно должно выглядеть так, как показано на следующем рисунке. Your window should resemble the following illustration.

Разметка XAML теперь должна выглядеть следующим образом: The XAML markup should now look similar to the following example:

Добавление кода к кнопке Display Add code to the display button

После запуска приложения окно сообщения появится только тогда, когда пользователь выберет переключатель, а затем нажмет кнопку Display. When this application runs, a message box appears after a user chooses a radio button and then chooses the Display button. Одно окно сообщения появится для Hello, и другое — для Goodbye. One message box will appear for Hello, and another will appear for Goodbye. Чтобы задать такое поведение, добавьте код в событие Button_Click в файле Greetings.xaml.cs. To create this behavior, you’ll add code to the Button_Click event in Greetings.xaml.cs.

На поверхности разработки дважды щелкните кнопку Display . On the design surface, double-click the Display button.

Откроется файл Greetings.xaml.cs, а курсор будет установлен на событии Button_Click . Greetings.xaml.cs opens, with the cursor in the Button_Click event.

Введите следующий код: Enter the following code:

Сохраните приложение. Save the application.

Отладка и тестирование приложения Debug and test the application

После этого вам предстоит отладить приложение для выявления ошибок и тестирования того, что оба окна сообщений отображаются правильно. Next, you’ll debug the application to look for errors and test that both message boxes appear correctly. Приведенные ниже инструкции описывают, как выполнить сборку и запустить отладчик (дополнительные сведения см. в разделах Построение приложения WPF и Отладка WPF). The following instructions tell you how to build and launch the debugger, but later you might read Build a WPF application (WPF) and Debug WPF for more information.

Поиск и исправление ошибок Find and fix errors

В этом шаге вам предстоит найти ошибку, которую мы намеренно допустили ранее, изменив имя файла MainWindow.xaml. In this step, you’ll find the error that we caused earlier by changing the name of the MainWindow.xaml file.

Начало отладки и поиск ошибки Start debugging and find the error

Запустите отладчик, нажав клавишу F5 или выбрав пункты меню Отладка и Начать отладку. Start the debugger by pressing F5 or selecting Debug, then Start Debugging.

Появится окно Режим приостановки выполнения, а в окне Вывод будет указано, что произошло исключение IOException: «Не удается найти ресурс mainwindow.xaml». A Break Mode window appears, and the Output window indicates that an IOException has occurred: Cannot locate resource ‘mainwindow.xaml’.

Остановите отладчик, выбрав в меню Отладка > Остановить отладку. Stop the debugger by choosing Debug > Stop Debugging.

Мы переименовали MainWindow.xaml в Greetings.xaml в начале этого руководства, но код приложения по-прежнему ссылается на MainWindow.xaml как универсальный код ресурса (URI), поэтому проект не может быть запущен. We renamed MainWindow.xaml to Greetings.xaml at the start of this tutorial, but the code still refers to MainWindow.xaml as the startup URI for the application, so the project can’t start.

Задание Greetings.xaml в качестве начального универсального кода ресурса (URI) Specify Greetings.xaml as the startup URI

В обозревателе решений откройте файл App.xaml. In Solution Explorer, open the App.xaml file.

Измените StartupUri=»MainWindow.xaml» на StartupUri=»Greetings.xaml» и сохраните изменения. Change StartupUri=»MainWindow.xaml» to StartupUri=»Greetings.xaml» , and then save the changes.

Запустите отладчик снова (клавишей F5). Start the debugger again (press F5). Должно появиться окно Greetings приложения. You should see the Greetings window of the application.

Теперь закройте окно приложения, чтобы остановить отладку. Now close the application window to stop debugging.

Отладка с точками останова Debug with breakpoints

Добавив точки останова, можно тестировать код во время отладки. You can test the code during debugging by adding some breakpoints. Точки останова можно добавлять, выбирая в меню Отладка > Точка останова, щелкая в левом поле редактора рядом со строкой кода, в которой требуется приостановить выполнение, или нажимая клавишу F9. You can add breakpoints by choosing Debug > Toggle Breakpoint, by clicking in the left margin of the editor next to the line of code where you want the break to occur, or by pressing F9.

Добавление точек останова Add breakpoints

Откройте файл Greetings.xaml.cs и выделите строку MessageBox.Show(«Hello.») . Open Greetings.xaml.cs, and select the following line: MessageBox.Show(«Hello.»)

Добавьте точку останова, выбрав меню Отладка, затем — Точка останова. Add a breakpoint from the menu by selecting Debug, then Toggle Breakpoint.

Рядом со строкой кода в крайнем левом поле окна редактора появится красный кружок. A red circle appears next to the line of code in the far left margin of the editor window.

Выделите следующую строку: MessageBox.Show(«Goodbye.») . Select the following line: MessageBox.Show(«Goodbye.») .

Нажмите клавишу F9, чтобы добавить точку останова, а затем нажмите клавишу F5, чтобы начать отладку. Press the F9 key to add a breakpoint, and then press F5 to start debugging.

В окне Greetings выберите переключатель Hello и нажмите кнопку Display . In the Greetings window, choose the Hello radio button, and then choose the Display button.

Строка MessageBox.Show(«Hello.») выделяется желтым цветом. The line MessageBox.Show(«Hello.») is highlighted in yellow. В нижней части интегрированной среды разработки слева закреплены окна «Видимые», «Локальные» и «Контрольные значения», а справа — окна «Стек вызовов», «Точки останова», «Параметры исключений», «Команда», «Интерпретация» и «Вывод». At the bottom of the IDE, the Autos, Locals, and Watch windows are docked together on the left side, and the Call Stack, Breakpoints, Exception Settings, Command, Immediate, and Output windows are docked together on the right side.

В строке меню выберите Отладка > Шаг с выходом. On the menu bar, choose Debug > Step Out.

Приложение возобновит выполнение, и появится окно сообщения со словом «Hello». The application resumes execution, and a message box with the word «Hello» appears.

Нажмите кнопку ОК в окне сообщения, чтобы закрыть его. Choose the OK button on the message box to close it.

В окне Greetings выберите переключатель Goodbye и нажмите кнопку Display . In the Greetings window, choose the Goodbye radio button, and then choose the Display button.

Строка MessageBox.Show(«Goodbye.») выделяется желтым цветом. The line MessageBox.Show(«Goodbye.») is highlighted in yellow.

Нажмите клавишу F5, чтобы продолжить отладку. Choose the F5 key to continue debugging. Когда появится окно сообщения, нажмите в нем кнопку ОК , чтобы закрыть его. When the message box appears, choose the OK button on the message box to close it.

Закройте окно приложения, чтобы остановить отладку. Close the application window to stop debugging.

В строке меню выберите Отладка > Выключить все точки останова. On the menu bar, choose Debug > Disable All Breakpoints.

Просмотр представления элементов пользовательского интерфейса View a representation of the UI elements

В работающем приложении в верхней части окна должно отображаться мини-приложение. In the running app, you should see a widget that appears at the top of your window. Это вспомогательное средство времени выполнения, обеспечивающее быстрый доступ к некоторым полезным функциям отладки. This is a runtime helper that provides quick access to some helpful debugging features. Нажмите первую кнопку, которая называется Перейти к динамическому визуальному дереву. Click on the first button, Go to Live Visual Tree. Должно отобразиться окно с деревом, содержащим все визуальные элементы страницы. You should see a window with a tree that contains all the visual elements of your page. Разверните узлы, чтобы найти добавленные кнопки. Expand the nodes to find the buttons you added.

Сборка окончательной версии приложения Build a release version of the application

Теперь, когда вы проверили, что все работает, можно подготовить окончательную сборку приложения. Now that you’ve verified that everything works, you can prepare a release build of the application.

Выберите в главном меню Сборка > Очистить решение для удаления промежуточных файлов и выходных файлов, которые были созданы в ходе предыдущих сборок. On the main menu, select Build > Clean solution to delete intermediate files and output files that were created during previous builds. Это действие не является обязательным, но оно позволяет очистить результаты отладочной сборки. This isn’t necessary, but it cleans up the debug build outputs.

Измените конфигурацию сборки для HelloWPFApp с Отладка на Выпуск с помощью раскрывающегося списка на панели инструментов (сейчас это «Отладка»). Change the build configuration for HelloWPFApp from Debug to Release by using the dropdown control on the toolbar (it says «Debug» currently).

Выполните сборку решения, выбрав Сборка > Собрать решение. Build the solution by choosing Build > Build Solution.

Поздравляем с завершением этого учебника! Congratulations on completing this tutorial! Построенный файл .exe находится в каталоге решения и проекта ( . \HelloWPFApp\HelloWPFApp\bin\Release). You can find the .exe you built under your solution and project directory (. \HelloWPFApp\HelloWPFApp\bin\Release).

Следующие шаги Next steps

Поздравляем с завершением этого учебника! Congratulations on completing this tutorial! Для получения дополнительных сведений перейдите к следующим руководствам. To learn even more, continue with the following tutorials.

Читайте также:  Графический интерфейс для linux debian
Оцените статью