Hello World App with WPF in C# - Visual Studio (Windows) (2023)

  • Article

Refers to: Hello World App with WPF in C# - Visual Studio (Windows) (1)eye studioHello World App with WPF in C# - Visual Studio (Windows) (2)Visual Studio for MacHello World App with WPF in C# - Visual Studio (Windows) (3)visual studio code

After completing this tutorial, you'll become familiar with the many tools, dialog boxes, and designers that you can use when developing applications in Visual Studio. You will create a "Hello World" application, design the user interface, add code and debug errors while learning to work in an integrated development environment (IDE).

previous requirements

  • If you haven't installed Visual Studio yet, go toVisual Studio downloadwebsite to install it for free.
  • Make sure thatBuilding .NET desktopsload is installed. You can check this in the Visual Studio installer.
  • You can use .NET Framework or .NET Core for this tutorial. .NET Core is the latest and most modern framework. .NET Core requires Visual Studio 2019 version 16.3 or later.

What is WPF?

WPF, or Windows Presentation Foundation, is a user interface (UI) platform that builds desktop client applications. The WPF development platform supports a rich set of application development features, including the application model, resources, controls, graphics, layout, data binding, documents, and security.

WPF is part of the .NET framework, so if you've built .NET applications using ASP.NET or Windows Forms before, the development environment should feel familiar. WPF uses an extensible application markup languageXAMLProvide a declarative application programming model. For more information, seeOverview of WPF.NET.

configure the IDE

When you start Visual Studio, the run window opens first. To choosecontinue without codeto open the development environment. You will see tool windows, menus and toolbars, and the space of the main window. Tool windows are docked to the left and right of the application window. The search box, menu bar, and standard toolbar are at the top. When a solution or project is loaded, editors and designers appear in the middle of the application window. When you develop an application, you spend most of your time in this central area.

create a project

When you create an application in Visual Studio, you first create a project and a solution. In this example, you'll create a Windows Presentation Foundation (WPF) project.

  1. Abra Visual Studio.

  2. In the start window, selectCreate a new project.

    Hello World App with WPF in C# - Visual Studio (Windows) (4)

  3. Oh noCreate a new projectscreen, search for "WPF", selectWPF applicationthen selectNext.

    Hello World App with WPF in C# - Visual Studio (Windows) (5)

  4. On the next screen give the project a name,WitajWPFAppand chooseNext.

    Hello World App with WPF in C# - Visual Studio (Windows) (6)

  5. IncludingAdditional informationventilation,.NET Core 3.1should already be selected for the target frame. If not, choose.NET Core 3.1. then selectCreate.

    Hello World App with WPF in C# - Visual Studio (Windows) (7)

Visual Studio creates the HelloWPFApp project and solution as wellsolution explorershows different files. HeWPF designerdisplays layout view and XAML viewVentana.xaml main filein split view. You can move the divider to show more or less of any view. You can choose to display only the visual view or only the XAML view.

Hello World App with WPF in C# - Visual Studio (Windows) (8)

Use

For more information on XAML (Extensible Application Markup Language), seeXAML overview for WPFside.

After creating the project, you can customize it. To do this, selectProperties windowzViewmenu, press itF4. You can then view and change options for design elements, controls, and more in the app.

Hello World App with WPF in C# - Visual Studio (Windows) (9)

  1. Abra Visual Studio.

  2. In the start window, selectCreate a new project.

    Hello World App with WPF in C# - Visual Studio (Windows) (10)

  3. Oh noCreate a new projectscreen, search for "WPF", selectWPF applicationthen selectNext.

    Hello World App with WPF in C# - Visual Studio (Windows) (11)

  4. On the next screen give the project a name,WitajWPFAppand chooseNext.

    Hello World App with WPF in C# - Visual Studio (Windows) (12)

  5. IncludingAdditional informationventilation,.NET 6.0 (wsparcie długoterminowe)should already be selected for the target frame. If not, choose.NET 6.0 (long-term support). then selectCreate.

    Hello World App with WPF in C# - Visual Studio (Windows) (13)

Visual Studio creates the HelloWPFApp project and solution as wellsolution explorershows different files. HeWPF designerdisplays layout view and XAML viewVentana.xaml main filein split view. You can move the divider to show more or less of any view. You can choose to display only the visual view or only the XAML view.

Hello World App with WPF in C# - Visual Studio (Windows) (14)

Use

For more information on XAML (Extensible Application Markup Language), seeXAML overview for WPFside.

After creating the project, you can customize it. To do this, selectProperties windowzViewmenu, press itF4. You can then view and change options for design elements, controls, and more in the app.

Hello World App with WPF in C# - Visual Studio (Windows) (15)

Design a user interface (UI)

If the designer is not open, selectVentana.xaml main fileand pressChange+F7to open the designer.

We will add three types of controls to this application: atext blockcontrolStarting the radiocontrols and aButtoncontrol.

Add a TextBlock control

  1. PressControl+Qto activate the search box and enterToolbox. To chooseView > Toolboxfrom the results list.

  2. IncludingToolbox, expandCommon WPF controlsnode to display the TextBlock control.

    Hello World App with WPF in C# - Visual Studio (Windows) (16)

  3. Add a TextBlock control to the design surface by selecting an optiontext blockelement and dragging it to a window on the design surface. Center the control near the top of the window. In Visual Studio 2019 and later, you can use red tips to center the control.

    Your window should look like the image below:

    Hello World App with WPF in C# - Visual Studio (Windows) (17)

    The XAML markup should resemble the following example:

     
  1. PressControl+Qto activate the search box and enterToolbox. To chooseView > Toolboxfrom the results list.

  2. IncludingToolbox, expandCommon WPF controlsnode to display the TextBlock control.

    Hello World App with WPF in C# - Visual Studio (Windows) (18)

  3. Add a TextBlock control to the design surface by selecting an optiontext blockelement and dragging it to a window on the design surface. Center the control near the top of the window. You can use guides to center the control.

    Your window should look like the image below:

    Hello World App with WPF in C# - Visual Studio (Windows) (19)

    The XAML markup should resemble the following example:

     

Customize the text in the text block.

  1. In the XAML view, find the tag fortext blockand changeTextattributeTextboxASelect a message option, then select the Show button.

    The XAML markup should resemble the following example:

     
  2. If you want, re-center the TextBlock and then save your changes by pressingCtrl+Sor usingArchivesmenu option.

Then you add twoStarting the radiocontrols to the form.

Add radio buttons

  1. IncludingToolbox, to findStarting the radiocontrol.

    Hello World App with WPF in C# - Visual Studio (Windows) (20)

  2. Add two RadioButton controls to the design surface by selectingStarting the radioelement and dragging it to a window on the design surface. Move the buttons (by selecting them and using the arrow keys) so that they appear next to each other under the TextBlock control. Use the red guides to align the controls.

    Your window should look like this:

    Hello World App with WPF in C# - Visual Studio (Windows) (21)

  3. Includingreal estatewindow for the left RadioButton control, changeNameproperty (real estate on topreal estatewindow) tohello button.

    Hello World App with WPF in C# - Visual Studio (Windows) (22)

  4. Includingreal estatewindow of the right RadioButton control, changeNameownership to"Goodbye" button.then save your changes.

Next, you'll add the display text for each RadioButton control. The following procedure updates the fileContentsA property of the RadioButton control.

  1. IncludingToolbox, to findStarting the radiocontrol.

    Hello World App with WPF in C# - Visual Studio (Windows) (23)

  2. Add two RadioButton controls to the design surface by selectingStarting the radioelement and dragging it to a window on the design surface. Move the buttons (by selecting them and using the arrow keys) so that they appear next to each other under the TextBlock control. You can use the tips to align the controls.

    Your window should look like this:

    Hello World App with WPF in C# - Visual Studio (Windows) (24)

  3. Includingreal estatewindow for the left RadioButton control, changeNameproperty (real estate on topreal estatewindow) tohello button.

    Hello World App with WPF in C# - Visual Studio (Windows) (25)

  4. Includingreal estatewindow of the right RadioButton control, changeNameownership to"Goodbye" button.then save your changes.

Next, you'll add the display text for each RadioButton control. The following procedure updates the fileContentsA property of the RadioButton control.

Add the text displayed for each option button

  1. UpdateContentsattribute forhello buttony"Goodbye" button.A„Hola”y"Bye bye"in XAML. The XAML markup should now look similar to the example below:

       

Set the radio button to be selected by default

In this step, we'll set the HelloButton option to be checked by default so that one of the two radio buttons is always selected.

  1. In the XAML view, find the HelloButton tag.

  2. to addThis is checkedattribute and set it toTRUE. Specifically addIs checked = "True".

    The XAML markup should now look similar to the example below:

       

The last UI element you will add isButtoncontrol.

Add button control

  1. IncludingToolbox, to findButtonand then add it to the design surface below the RadioButton controls by dragging it onto the form in design view. If you're using Visual Studio 2019 or later, the red line helps center the control.

  2. In the XAML view, change the valueContentsto be controlled with the z buttonsContent="Button"AContent="Screen"then save your changes.

    Your window should look like the image below.

    Hello World App with WPF in C# - Visual Studio (Windows) (26)

    The XAML markup should now look similar to the example below:

        
  1. IncludingToolbox, to findButtonand then add it to the design surface below the RadioButton controls by dragging it onto the form in design view. Guidelines can help you control your focus.

  2. In the XAML view, change the valueContentsto be controlled with the z buttonsContent="Button"AContent="Screen"then save your changes.

    Your window should look like the screenshot below.

    Hello World App with WPF in C# - Visual Studio (Windows) (27)

    The XAML markup should now look similar to the example below:

        

Add the code to the display button

When this application is launched, a message box pops up after the user selects radio button and then optionTo showbutton. A "Hello" and "Goodbye" message box will appear. To create this behavior, you'll add code to the filebutton_clickevent inMain file Ventana.xaml.cs.

  1. On the design surface, double-click the fileTo showbutton.

    Main file Ventana.xaml.csopens by hovering overbutton_clickevent.

    Private invalid Button_Click(object sender, RoutedEventArgs e){}
  2. Enter the following code:

    if (HelloButton.IsChecked == true){ MessageBox.Show("Hola.");}si nie, if (GoodbyeButton.IsChecked == true){ MessageBox.Show("Adie.");}
  3. Save the app.

When this application is launched, a message box pops up after the user selects radio button and then optionTo showbutton. A "Hello" and "Goodbye" message box will appear. To create this behavior, you'll add code to the filebutton_clickevent inMain file Ventana.xaml.cs.

  1. On the design surface, double-click the fileTo showbutton.

    Main file Ventana.xaml.csopens by hovering overbutton_clickevent.

    Private invalid Button_Click(object sender, RoutedEventArgs e){}
  2. Enter the following code:

    if (HelloButton.IsChecked == true){ MessageBox.Show("Hola.");}si nie, if (GoodbyeButton.IsChecked == true){ MessageBox.Show("Adie.");}
  3. Save the app.

Debug and test the application

You will then debug the application to find errors and verify that both message boxes appear correctly. The instructions below describe how to build and run the debugger, but you can read them laterBuilding a WPF Application (WPF)yDebuguj WPFfor more information.

Rename the MainWindow.xaml file

Let's give MainWindow a more specific name. INsolution explorer, right-clickVentana.xaml main fileand chooseRename. Rename the file toRegards.xaml.

Find and fix bugs

In this step you will find the error we caused earlier by renaming the fileVentana.xaml main filearchives.

Start debugging and find the error.

  1. Start the debugger by pressingF5or by selectingDebug, Sostart debugging.

    Arest modeThe i window will appearProductionThe window indicates that an IOException occurred: The resource 'mainwindow.xaml' could not be located.

    Hello World App with WPF in C# - Visual Studio (Windows) (28)

  2. Stop the debugger by selectingDebug>stop debugging.

we change the nameVentana.xaml main fileARegards.xamlbut the code still refers toVentana.xaml main fileas the application launch URI, so the project cannot start.

  1. Start the debugger by pressingF5or by selectingDebug, Sostart debugging.

    Arest modeThe i window will appearProductionThe window indicates that an IOException occurred: The resource 'mainwindow.xaml' could not be located.

    Hello World App with WPF in C# - Visual Studio (Windows) (29)

  2. Stop the debugger by selectingDebug>stop debugging.

we change the nameVentana.xaml main fileARegards.xamlat the beginning of this tutorial, but the code is still referencedVentana.xaml main fileas the application launch URI, so the project cannot start.

Specify the Greetings.xaml file as the starting URI

  1. Wsolution explorer, openapplication.xamlarchives.

  2. ChangeStartupUri="Main file Ventana.xaml"AStartupUri="Greetings.xaml"and save changes.

As an optional step, you will avoid confusion if you change the title of the application window to match the new name.

  1. Wsolution explorer, openRegards.xamlthe file that was just renamed.

  2. Change the valuewindow.titlepropertyTitle="Main window"ATitle="Greetings"and save changes.

Restart the debugger (pressF5). You should see nowRegardsapplication window.

Hello World App with WPF in C# - Visual Studio (Windows) (30)

Hello World App with WPF in C# - Visual Studio (Windows) (31)

Now close the application window to stop debugging.

Debug with breakpoints

You can test your code while debugging by adding some breakpoints. You can add breakpoints by selectingDebug>toggle breakpointby clicking in the editor's left margin next to the line of code where you want to break, or by pressingF9.

Add breakpoints

  1. openRegards.xaml.csand select the following line:MessageBox.Show("Hola.")

  2. Add a breakpoint from the menu by selectingDebug, Sotoggle breakpoint.

    A red circle will appear next to the line of code in the left margin of the editor window.

  3. Select the following line:MessageBox.Show("Goodbye.").

  4. pressF9to add a breakpoint, then tapF5to start debugging.

  5. IncludingRegardswindow, selectHolaradio button, then select an optionTo showbutton.

    The lineMessageBox.Show("Hola.")is highlighted in yellow. At the bottom of the IDE, the Autos, Locales, and Watch windows are docked together on the left, and the Call Stack, Breakpoints, Exception Settings, Command, Immediate, and Exit windows are docked on the right.

    Hello World App with WPF in C# - Visual Studio (Windows) (32)

  6. In the menu bar, selectDebug>Go out.

    The application resumes and a message box with the word "Hello" appears.

  7. ChooseOKin the message box to close it.

  8. IncludingRegardswindow, selectGoodbyeradio button, then select an optionTo showbutton.

    The lineMessageBox.Show("Goodbye.")is highlighted in yellow.

  9. ChooseF5key to continue debugging. When the message box appears, select an optionOKin the message box to close it.

  10. Close the application window to stop debugging.

  11. In the menu bar, selectDebug>Disable all breakpoints.

  1. openRegards.xaml.csand select the following line:MessageBox.Show("Hola.")

  2. Add a breakpoint from the menu by selectingDebug, Sotoggle breakpoint.

    A red circle will appear next to the line of code in the left margin of the editor window.

  3. Select the following line:MessageBox.Show("Goodbye.").

  4. pressF9to add a breakpoint, then tapF5to start debugging.

  5. IncludingRegardswindow, selectHolaradio button, then select an optionTo showbutton.

    The lineMessageBox.Show("Hola.")is highlighted in yellow. At the bottom of the IDE, the Autos, Locales, and Watch windows are docked together on the left, and the Call Stack, Breakpoints, Exception Settings, Command, Immediate, and Exit windows are docked on the right.

    Hello World App with WPF in C# - Visual Studio (Windows) (33)

  6. In the menu bar, selectDebug>Go out.

    The application resumes and a message box with the word "Hello" appears.

  7. ChooseOKin the message box to close it.

  8. IncludingRegardswindow, selectGoodbyeradio button, then select an optionTo showbutton.

    The lineMessageBox.Show("Goodbye.")is highlighted in yellow.

  9. ChooseF5key to continue debugging. When the message box appears, select an optionOKin the message box to close it.

  10. Close the application window to stop debugging.

  11. In the menu bar, selectDebug>Disable all breakpoints.

Display a representation of the user interface elements.

In the running application, a widget should appear at the top of the window. The widget is an executive helper that gives you quick access to some useful debugging features. Select the first buttonGo to the live visual tree. You should see a window with a tree containing all the visual elements of your page. Expand the nodes to find the added buttons.

Hello World App with WPF in C# - Visual Studio (Windows) (34)

Hello World App with WPF in C# - Visual Studio (Windows) (35)

Create an app version.

Now that you've verified that everything works, you can prepare a rough version of your application.

  1. In the main menu, selectBuild>clean solutionto remove intermediate files and output files that were created during previous builds. This step is not required, but it does clean up the debug build output.

  2. Change the build configuration for HelloWPFApp fromDebugAReleaseusing the drop down control on the toolbar (currently it says "Debug").

  3. Build a solution by choosingBuild>build the solution.

Congratulations on completing this tutorial! you can find.execreated in the solutions and projects directory (...\HelloWPFApp\HelloWPFApp\bin\Release).

Next steps

Congratulations on completing this tutorial! To learn even more, check out the tutorials below.

Continue with more WPF tutorials

See also

  • Productivity Tips

Comment

Send and view reviews for

References

Top Articles
Latest Posts
Article information

Author: Edmund Hettinger DC

Last Updated: 09/10/2023

Views: 5859

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.