Part1 - The Basics of WPF IU

Video: https://youtu.be/Vjldip84CXQ

#Csharp #Computer_Science

Previous Part | Next Part 🔜

↩️ Go Back

Table of Contents:


A) Objective - Create a UI

This is the first in a series of tutorials on WPF, which is a framework for creating modern UIs in Windows.

We have a screenshot of a UI we want to create, which is a real request from someone. This is how we want it to look.

We're going to build this exact UI in WPF to give you an introduction to creating WPF applications, including working with:

We'll use this template as a guide.


B) STEP1 - Create a New Project in Visual Studio

Let's begin by opening Visual Studio,

|300

and creating a new project. I want a WPF application using Visual C#. We’ll call this project "Wpf Basics."

By creating this WPF application, you'll get an AssemblyInfo.cs file,

an App.config file that contains the framework version,

and an App.xaml file.

If you right-click on the XAML file and select "View Code,"

you'll see it has a code-behind file.

Also, double-clicking on the XAML file will show you a small amount of XAML, which is essentially XML.

Here is the main window, which is the startup window for the application.

When you create a WPF application, this window opens by default. Pressing F5 compiles and runs the project, which generates a blank window.

This blank WPF window is what we’re going to modify.

The structure of the window is similar to HTML—you start with an angle bracket, type the tag and attributes, and close the angle bracket.

Everything inside the opening and closing tags is contained within that element.

You can only have a single top-level element in the window, so it must be a container element.

In WPF, I typically type directly into the XAML file while watching the window preview to see what I'm creating.

You can use the toolbar to drag and drop controls,

but I prefer to write them manually. I’ll explain my thought process as we build the application.

Let’s resize the window slightly, zoom out to 100%, and hide the toolbar. Now, let’s take a look at the screenshot. It shows buttons at the top, properties below, and checkboxes on the side. The first thing I do when examining any UI is break it down into parts. In WPF, there are two main container elements: the StackPanel and the Grid. A StackPanel is an element that stacks items one after another, either vertically or horizontally, depending on the orientation.

03:30
For example, this label will only take up as much space as needed, and the box below will be positioned right beneath it. This is how a StackPanel stacks elements. You can stack them vertically or horizontally. If you need more than a straight stack, like in this case where we have two rows, you'll need to use a Grid. A Grid can have multiple rows and columns, and you can place StackPanels inside of it to organize sections.

04:03
So, when breaking down a UI, start with a container element. In this case, the entire UI flows vertically, so we’ll begin with a StackPanel to stack elements one on top of the other. We’ll replace the Grid in the XAML with a StackPanel. Let me show you what I mean—if I add a button inside the StackPanel and then paste three buttons in total, you’ll see that they stack one on top of the other. Each button takes up only as much room as it needs and no more.

05:05
That's the behavior of a StackPanel. In contrast, a Grid takes up all the available space. By default, a Grid has a single row and column, so the buttons stack on top of each other, even though they’re invisible due to overlap. Let’s stick with the StackPanel for now and continue creating this form.

05:33
Now, let’s stack downwards. You could use a StackPanel to stack three buttons horizontally, but let me show you what happens when you do. The main StackPanel is the outer container holding everything. Inside this, we could use another StackPanel with a horizontal orientation to stack the buttons side by side. However, a StackPanel only takes up the space it needs, so each button will still be of varying sizes.

06:11
Looking at the screenshot, the buttons are evenly divided, so instead of using a StackPanel, we’ll switch to a Grid with three equally spaced columns. Let’s replace the inner StackPanel with a Grid, remove the orientation setting, and define three columns using ColumnDefinitions. Each column will be set to take up one-third of the space by using the * syntax, which divides the available space equally.

07:23
Now, we have three equally spaced columns in the Grid. We’ll place the three buttons inside these columns. The buttons will be labeled "Apply," "Reset," and "Refresh." To position them correctly, we’ll specify the column each button belongs to using the Grid.Column attribute, which starts at index 0.

08:28
Next, let’s focus on spacing. We don’t want the buttons right against the edge of the screen, so we’ll add padding by wrapping the entire StackPanel in a Border and setting its padding to 10. This creates some space between the buttons and the edge of the screen. We also need to add spacing between the buttons. To do this, we’ll add margins to the buttons. We’ll specify different margins for the left, top, right, and bottom to create proper spacing between the buttons.

10:34
At this point, we’ve completed the top section with three evenly spaced buttons. The StackPanel is stacking everything down, and the Grid holds the buttons. The border we added provides padding around the entire section.

11:12
Next, we need to add the title "Pulse Properties" below the buttons. We’ll use a TextBlock for this because a label is more limited in functionality. Let’s add a TextBlock, set its text to "Pulse Properties," and apply a bold font style. We also need to add some spacing above and below the title using the Margin property.

12:15
After the title, we need to add a description label. We’ll use another TextBlock, but this time without the bold styling. Below the description, we need to add a text entry field where the user can type something. This is done using a TextBox.

13:52
When the TextBox is first created, there’s very little space inside, making the text look cramped. To fix this, we’ll add padding inside the TextBox. Padding adds space on the inside, while margins add space on the outside.

14:57
Next, we’ll add the status and revision fields. These need to be side by side, so we’ll use another Grid with two columns. The first column will be twice the size of the second. Inside each column, we’ll stack the labels and text boxes using StackPanels.

16:58
To indicate that the status and revision fields are read-only, we’ll disable user input by setting the IsReadOnly property to true. We’ll also adjust the background color to a light gray to visually differentiate these fields from the editable ones.

18:37
Next, we’ll create a part number field below the revision field, which will also be read-only. Again, we’ll copy and paste some of the previous XAML to save time. After that, we’ll create the material field using a ComboBox (dropdown menu).

19:57
We’ll define items for the ComboBox and set the default selected index to zero, so the first item is selected by default. After this, we’ll create the manufacturing information section, which includes another ComboBox and several checkboxes.

21:57
For the checkboxes, we’ll create another Grid with two columns, and inside each column, we’ll stack the checkboxes vertically using StackPanels.

23:42
By this point, we’ve made significant progress. We have buttons, text fields, ComboBoxes, and checkboxes in place. One of the benefits of using a Grid and StackPanel combination is that the UI scales properly when the window is resized. Elements remain proportional because they are sized relatively.

24:22
We’ll continue adding more fields, including length and mass, which are read-only. After that, we’ll add a finish dropdown, similar to the material field, with preset values. Then we’ll add a supplier name and supplier code field, similar to the other read-only fields.

28:04
By pressing F5, we can see that the entire form is now complete. We can compare the form to the screenshot and see that we’ve accurately recreated the UI. While there are minor details we could tweak, such as adding more spacing, the form is functional and demonstrates how quickly you can build a UI once you’re familiar with WPF.

28:39
Now let’s review the structure. When you create a WPF window, you need one top-level container. In this case, we used a StackPanel inside a Border, which adds padding around the entire UI. The StackPanel stacks elements vertically. Inside this, we used a Grid to organize the buttons, and each section of the form was broken down similarly into grids and stack panels. You can also add comments in the XAML to help keep track of sections as your code gets longer.

31:18
You can think of the XAML structure like a tree, with indentation representing hierarchy. For example, the StackPanel is inside the Border, the Grid is inside the StackPanel, and the buttons are inside the Grid. Visual Studio helps with this by automatically formatting your XAML as you type, closing tags for you, and warning you if there are mistakes.

32:47
Although, you can drag and drop controls from the Toolbox, it can sometimes add unnecessary properties or position controls unpredictably. This is why I prefer typing the XAML manually, as it gives you more control and keeps your code cleaner. When building a UI, always ask yourself: do I need a StackPanel to stack items, or a Grid to control layout? These two elements will cover most of your UI layout needs.

35:26
Now, let's move on to making the form interactive. We’ll start by adding functionality to the "Apply" button. In order to interact with controls in code, you need to give them a name. For example, we’ll name the "Apply" button applyButton using the x:Name attribute. Then, we’ll create a click event handler for the button, which will run whenever the button is clicked.

36:31
In the code-behind file, the click event handler is generated automatically when you define it in the XAML. Now, we can access the button and other controls using their names. For example, we’ll retrieve the text from the description TextBox when the "Apply" button is clicked and display it in a message box.

38:29
Let’s continue by adding functionality to the "Reset" button. When this button is clicked, we want to reset all the checkboxes. We’ll name each checkbox and create a reset event that sets all of them to unchecked.

41:32
Now, let’s handle what happens when a checkbox is checked. We’ll create a universal function that runs whenever any checkbox is clicked. This function will retrieve the checkbox’s content (its label) and append it to the length TextBox. To do this, we cast the sender object to a Checkbox and retrieve its content.

45:35
Next, let’s add functionality to the ComboBox. When the selected item changes, we’ll display the selected value in the note field. We’ll retrieve the selected item by casting the sender to a ComboBox and accessing the SelectedValue. If there is no initial value, we can set it programmatically when the form first loads by triggering the selection changed event.

51:38
So far, we’ve created a functional UI that interacts with various controls. We've covered buttons, text fields, checkboxes, and ComboBoxes. In future videos, we’ll explore advanced topics like view models and styling. We’ll also focus on keeping the code organized by separating logic from the UI using view models, which is considered best practice in WPF development.

54:48
For now, take some time to experiment with different controls and layouts in WPF. Try changing the background colors, orientations, and other properties to see how they affect the UI. Hopefully, this has been a good introduction to WPF, and I look forward to diving deeper into more advanced topics in future tutorials.


Previous Part | Next Part 🔜

↩️ Go Back


Z) 🗃️ Glossary

File Definition
Uncreated files Origin Note