- Пошаговое руководство. Использование функций редактора XML Walkthrough: Use XML editor features
- Создание XML-файла и связывание его со схемой XML To create a new XML file and associate it with an XML schema
- Добавление данных To add data
- Форматирование XML-документа To format the XML document
- Сохранение XML-документа To save the XML document
- Файл hireDate.xsd hireDate.xsd file
- Создание приложения Windows Forms на C# в Visual Studio Create a Windows Forms app in Visual Studio with C#
- Создание проекта Create a project
- Создание приложения Create the application
- Добавление кнопки на форму Add a button to the form
- Добавление метки на форму Add a label to the form
- Добавление кода на форму Add code to the form
- Запуск приложения Run the application
- Следующие шаги Next steps
Пошаговое руководство. Использование функций редактора XML Walkthrough: Use XML editor features
В этом пошаговом руководстве подробно описан процесс создания нового XML-документа. The steps in this walkthrough show you how to create a new XML document. В нем также используются некоторые функции редактора XML, благодаря которым это приложение становится очень полезным при создании XML-документов. The walkthrough also uses some of the features of the XML editor that make it valuable for XML authoring.
Прежде чем начать работу с пошаговым руководством, сохраните файл hireDate.xsd (содержится ниже в данном разделе) на локальном компьютере. Before starting the walkthrough, save the hireDate.xsd file (included below in this topic) to your local computer.
Создание XML-файла и связывание его со схемой XML To create a new XML file and associate it with an XML schema
В меню Файл выберите пункт Создать, затем — Файл. On the File menu, point to New, and click File.
Выберите в области Шаблоны пункт XML-файл и нажмите кнопку Открыть. Select XML File in the Templates pane and click Open.
Новый файл открывается в редакторе. A new file is opened in the editor. Этот файл содержит XML-декларацию по умолчанию: . The file contains a default XML declaration, .
В окне свойств документа нажмите кнопку обзора ( . ) в поле Схемы. In the document properties window, click the browse button (. ) on the Schemas field.
Отобразится диалоговое окно XSD-схемы. The XSD Schemas dialog box is displayed.
Нажмите кнопку Добавить. Click Add.
Отображается диалоговое окно Открытие XSD-схемы. The Open XSD Schema dialog box is displayed.
Выберите файл hireDate.xsd и нажмите кнопку Открыть. Select the hireDate.xsd file and click Open.
Нажмите кнопку ОК. Click OK.
Теперь с XML-документом связана XML-схема. The XML Schema is now associated with the XML document. Эта XML-схема используется для проверки правильности документа. The XML Schema is used to validate the document. Также она используется технологией IntelliSense для заполнения списка допустимых элементов. It is also used by IntelliSense to populate the member list of valid elements.
Добавление данных To add data
Наберите на панели редактора. Type in the editor pane.
Список членов отображает следующие возможные элементы: The members list displays the possible items:
!— для добавления комментария. !— to add a comment.
!DOCTYPE для добавления типа документа. !DOCTYPE to add a document type.
? ? для добавления инструкции по обработке. to add a processing instruction.
сотрудник для добавления корневого элемента. employee to add the root element.
Выберите Select
Редактор вставляет закрывающий тег комментария и помещает курсор между открывающим и закрывающим тегами комментария. The editor inserts a comment end tag and places the cursor between the start and end comment tags.
Введите Test XML file. Type in Test XML file.
В новой строке введите и выберите сотрудника из списка членов. On a new line, type , and select employee from the member list.
Редактор добавляет начало XML-элемента, . The editor adds the start of an XML element, . В этот момент можно добавить в элемент атрибуты или закрыть открывающий тег, введя > . At this point you can add attributes to the element or you can close the start tag by typing > .
Введите знак > , чтобы закрыть тег. Type > to close the tag.
Редактор добавляет закрывающий тег. The editor adds the end tag. Закрывающий тег после добавления будет подчеркнут волнистой линией, обозначающей ошибку проверки правильности. The end tag is added with a wavy underline indicating a validation error. Всплывающая подсказка отображает сообщение: Содержимое элемента «сотрудник» неполно. Ожидается ID. The ToolTip displays the message: The element ’employee’ has incomplete content. Expected ‘ID’.
Введите знак и выберите ID из списка членов. Type and select ID from the member list. Затем введите > . Then type > .
Редактор добавляет XML-элемент, , и помещает курсор после открывающего тега ID. The editor adds the XML element, , and positions the cursor after the ID start tag.
Введите abc. Type abc.
Текст abc подчеркивается волнистой линией. The abc text has a wavy underline. Всплывающая подсказка отображает сообщение: Элемент «ID» имеет недопустимое значение для этого типа данных. The ToolTip displays the message: The ‘ID’ element has an invalid value according to its data type.
Щелкните правой кнопкой мыши элемент ID и выберите команду Перейти к определению. Right-click on the ID element and select Go To Definition.
Редактор открывает файл hireDate.xsd в новом окне документа и помещает курсор на определении элемента схемы ID. The editor opens the hireDate.xsd file in a new document window and positions the cursor on the ID schema element definition.
Вернитесь к XML-файлу и замените текст abc на 123. Return to the XML file, and replace the abc text with 123.
Волнистое подчеркивание и подсказка, относящиеся к элементу ID, удаляются. The wavy underline and ToolTip are cleared under the ID element value. Подсказка для закрывающего тега элемента «сотрудник» будет содержать сообщение: Содержимое элемента «сотрудник» неполно. Предполагается наличие элемента «дата найма» . The ToolTip for the employee end tag now displays the message: The element ’employee’ has incomplete content. Expected ‘hire-date’.
Поместите курсор после закрывающего тега ID, введите , выберите элемент дата найма из списка членов, а затем введите > . Place the cursor after the ID end tag, type in , select hire-date from the member list, and then type in > .
Редактор добавляет XML-элемент и помещает курсор после открывающего тега элемента «hire-date». The editor adds the XML element, , and positions the cursor after the hire-date start tag.
Введите 10.01.2003 в качестве значения даты найма. Type in 2003-01-10 for the hire-date value.
Форматирование XML-документа To format the XML document
Нажмите кнопку Форматировать документ на панели инструментов редактора XML или нажмите сочетание клавиш Ctrl+E,D. Select the Format Document button on the XML editor toolbar, or press Ctrl+E,D.
XML-документ будет переформатирован. The XML document is reformatted.
Сохранение XML-документа To save the XML document
В меню Файл щелкните Сохранить как. From the File menu, select Save As.
Отобразится диалоговое окно Сохранение файла. The Save File As dialog box is displayed. Имя файла по умолчанию — «XMLFile1» . The default filename is ‘XMLFile1’.
Введите имя файла и место сохранения для XML-документа и нажмите кнопку Сохранить. Enter the file name and location for the XML document and click Save.
Файл hireDate.xsd hireDate.xsd file
В этом пошаговом руководстве используется следующий файл схемы. The following schema file is used in this walkthrough:
Создание приложения Windows Forms на C# в Visual Studio Create a Windows Forms app in Visual Studio with C#
В рамках этого краткого знакомства с возможностями интегрированной среды разработки Visual Studio (IDE) вы создадите простое приложение на C# с пользовательским интерфейсом на основе Windows. In this short introduction to the Visual Studio integrated development environment (IDE), you’ll create a simple C# application that has a Windows-based user interface (UI).
Установите 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.
На некоторых снимках экрана в этом учебнике используется темная тема. Some of the screenshots in this tutorial use the dark theme. Если вы не используете темную тему, но хотите переключиться на нее, см. страницу Персонализация интегрированной среды разработки и редактора Visual Studio. If you aren’t using the dark theme but would like to, see the Personalize the Visual Studio IDE and Editor page to learn how.
Создание проекта Create a project
Сначала вы создадите проект приложения на C#. First, you’ll create a C# application project. Для этого типа проекта уже имеются все нужные файлы шаблонов, что избавляет вас от лишней работы. The project type comes with all the template files you’ll need, before you’ve even added anything.
Откройте Visual Studio 2017. Open Visual Studio 2017.
В верхней строке меню последовательно выберите Файл > Создать > Проект. From the top menu bar, choose File > New > Project.
В левой области диалогового окна Новый проект разверните узел Visual C# и выберите Рабочий стол Windows. In the New Project dialog box in the left pane, expand Visual C#, and then choose Windows Desktop. На средней панели выберите Приложение Windows Forms (.NET Framework) . In the middle pane, choose Windows Forms App (.NET Framework). Назовите файл HelloWorld . Then name the file HelloWorld .
Если шаблон проекта Приложение Windows Forms (.NET Framework) отсутствует, закройте диалоговое окно Новый проект и в верхней строке меню выберите Сервис > Получить средства и компоненты. If you don’t see the Windows Forms App (.NET Framework) project template, cancel out of the New Project dialog box and from the top menu bar, choose Tools > Get Tools and Features. Запускается Visual Studio Installer. The Visual Studio Installer launches. Выберите рабочую нагрузку .Разработка классических приложений .NET и затем элемент Изменить. Choose the .NET desktop development workload, then choose Modify.
Запустите Visual Studio 2019. Open Visual Studio 2019.
На начальном экране выберите Создать проект. On the start window, choose Create a new project.
В окне Создать проект выберите шаблон Приложение Windows Forms (.NET Framework) для C#. On the Create a new project window, choose the Windows Forms App (.NET Framework) template for C#.
(При желании вы можете уточнить условия поиска, чтобы быстро перейти к нужному шаблону. (If you prefer, you can refine your search to quickly get to the template you want. Например, введите Приложение Windows Forms в поле поиска. For example, enter or type Windows Forms App in the search box. Затем выберите C# в списке языков и Windows в списке платформ.) Next, choose C# from the Language list, and then choose Windows from the Platform list.)
Если шаблон Приложение Windows Forms (.NET Framework) отсутствует, его можно установить из окна Создание проекта. If you do not see the Windows Forms App (.NET Framework) template, you can install it from the Create a new project window. В сообщении Не нашли то, что искали? выберите ссылку Установка других средств и компонентов. In the Not finding what you’re looking for? message, choose the Install more tools and features link.
После этого в Visual Studio Installer выберите рабочую нагрузку Разработка классических приложений .NET. Next, in the Visual Studio Installer, choose the Choose the .NET desktop development workload.
Затем нажмите кнопку Изменить в Visual Studio Installer. After that, choose the Modify button in the Visual Studio Installer. Вам может быть предложено сохранить результаты работы; в таком случае сделайте это. You might be prompted to save your work; if so, do so. Выберите Продолжить, чтобы установить рабочую нагрузку. Next, choose Continue to install the workload. После этого вернитесь к шагу 2 в процедуре Создание проекта. Then, return to step 2 in this «Create a project» procedure.
В поле Имя проекта окна Настроить новый проект введите HelloWorld. In the Configure your new project window, type or enter HelloWorld in the Project name box. Затем нажмите Создать. Then, choose Create.
Новый проект открывается в Visual Studio. Visual Studio opens your new project.
Создание приложения Create the application
Когда вы выберете шаблон проекта C# и зададите имя файла, Visual Studio открывает форму. After you select your C# project template and name your file, Visual Studio opens a form for you. Форма является пользовательским интерфейсом Windows. A form is a Windows user interface. Мы создадим приложение Hello World, добавив элементы управления на форму, а затем запустим его. We’ll create a «Hello World» application by adding controls to the form, and then we’ll run the app.
Добавление кнопки на форму Add a button to the form
Щелкните Панель элементов, чтобы открыть всплывающее окно «Панель элементов». Choose Toolbox to open the Toolbox fly-out window.
(Если параметр для всплывающего окна Панель элементов отсутствует, его можно открыть в строке меню. (If you don’t see the Toolbox fly-out option, you can open it from the menu bar. Для этого выберите Вид > Панель элементов. To do so, View > Toolbox. Либо нажмите клавиши CTRL+ALT+X.) Or, press Ctrl+Alt+X.)
Щелкните значок Закрепить, чтобы закрепить окно Панель элементов. Choose the Pin icon to dock the Toolbox window.
Выберите элемент управления Кнопка и перетащите его на форму. Choose the Button control and then drag it onto the form.
В окне Свойства найдите элемент Текст, измените имя с Button1 на Click this , а затем нажмите клавишу ВВОД. In the Properties window, locate Text, change the name from Button1 to Click this , and then press Enter.
(Если окно Свойства не отображается, его можно открыть в строке меню.) (If you don’t see the Properties window, you can open it from the menu bar. Для этого выберите Вид > Окно свойств. To do so, choose View > Properties Window. Или нажмите клавишу F4.) Or, press F4.)
В разделе Проектирование окна Свойства измените имя с Button1 на btnClickThis , а затем нажмите клавишу ВВОД. In the Design section of the Properties window, change the name from Button1 to btnClickThis , and then press Enter.
Если список был упорядочен по алфавиту в окне Свойства, Button1 появится в разделе (DataBindings) . If you’ve alphabetized the list in the Properties window, Button1 appears in the (DataBindings) section, instead.
Добавление метки на форму Add a label to the form
Теперь, когда мы добавили элемент управления »Кнопка» для создания действия, давайте добавим элемент управления «Метка», куда можно отправлять текст. Now that we’ve added a button control to create an action, let’s add a label control to send text to.
Выберите элемент управления Метка в окне Панель элементов, а затем перетащите его на форму и расположите под кнопкой Нажмите это. Select the Label control from the Toolbox window, and then drag it onto the form and drop it beneath the Click this button.
В разделе Проект или (DataBindings) окна Свойства измените имя Label1 на lblHelloWorld и нажмите клавишу ВВОД. In either the Design section or the (DataBindings) section of the Properties window, change the name of Label1 to lblHelloWorld , and then press Enter.
Добавление кода на форму Add code to the form
В окне Form1.cs [Проект] дважды щелкните кнопку Нажмите это, чтобы открыть окно Form1.cs. In the Form1.cs [Design] window, double-click the Click this button to open the Form1.cs window.
(Кроме того, можно развернуть узел Form1.cs в обозревателе решений, а затем выбрать Form1.) (Alternatively, you can expand Form1.cs in Solution Explorer, and then choose Form1.)
В окне Form1.cs после строки private void введите lblHelloWorld.Text = «Hello World!»; , как показано на следующем снимке экрана: In the Form1.cs window, after the private void line, type or enter lblHelloWorld.Text = «Hello World!»; as shown in the following screenshot:
Запуск приложения Run the application
Нажмите кнопку Запустить, чтобы запустить приложение. Choose the Start button to run the application.
Будет выполнено несколько операций. Several things will happen. В интегрированной среде разработки Visual Studio откроются окна Средства диагностики и Вывод. In the Visual Studio IDE, the Diagnostics Tools window will open, and an Output window will open, too. Кроме того, вне этой среды откроется диалоговое окно Form1. But outside of the IDE, a Form1 dialog box appears. Оно будет содержать вашу кнопку Нажмите это и текст Label1. It will include your Click this button and text that says Label1.
Нажмите кнопку Нажмите это в диалоговом окне Form1. Choose the Click this button in the Form1 dialog box. Обратите внимание, что текст Label1 меняется на Hello World! . Notice that the Label1 text changes to Hello World!.
Закройте диалоговое окно Form1, чтобы завершить работу приложения. Close the Form1 dialog box to stop running the app.
Следующие шаги Next steps
Для получения дополнительных сведений перейдите к следующему руководству: To learn more, continue with the following tutorial: