WPF Development, Add Control

Windows Presentation Foundation (WPF) is a technology provided for creating rich user interfaces in the .NET framework. Using WPF, you can integrate graphics, text, video, and more to build appealing user interfaces. This article details how to add controls in WPF and practice the concepts of WPF through actual example code.

What is WPF?

WPF supports defining UI using XAML (Extensible Application Markup Language) and writing business logic in .NET languages like C#. The main advantages of WPF are as follows:

  • Data Binding: Allows binding between the UI and business data.
  • Templates and Styles: Provides flexible customization of the visual representation of various UI elements.
  • 3D Graphics Support: WPF supports 3D graphics, enabling the creation of more diverse UIs.
  • Direct Hardware Acceleration: WPF leverages GPU acceleration for better performance.

Adding Controls in WPF

To create a WPF application, you need to use a development environment like Visual Studio. The following steps show how to create a simple WPF application and add various basic controls.

1. Create a WPF Project

  1. Open Visual Studio and click “Create a new project.”
  2. Select “WPF App (.NET Core)” from the template list and click “Next.”
  3. After setting the project name and path, click “Create.”

2. Understanding the XAML File

The UI of a WPF application is defined in XAML files. The generated project typically includes App.xaml and MainWindow.xaml files. The MainWindow.xaml file contains the basic layout where various controls can be added.


<Window x:Class="MyWpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

    </Grid>
</Window>

3. Adding Basic Controls

Now it’s time to add various controls inside the Grid layout. Commonly used basic controls in WPF include Button, TextBox, Label, and ComboBox.

Adding a Button Control


<Button Name="myButton" Content="Click Me" Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Click="MyButton_Click"/>

Adding a TextBox Control


<TextBox Name="myTextBox" Width="200" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,50,0,0"/>

Adding a Label Control


<Label Content="Enter your name:" Width="120" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,100,0,0"/>

Adding a ComboBox Control


<ComboBox Name="myComboBox" Width="120" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,150,0,0">
    <ComboBoxItem Content="Option 1"/>
    <ComboBoxItem Content="Option 2"/>
    <ComboBoxItem Content="Option 3"/>
</ComboBox>

4. Full Code of the XAML File

Here is the complete code of the MainWindow.xaml file including all the added controls:


<Window x:Class="MyWpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label Content="Enter your name:" Width="120" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,100,0,0"/>
        <TextBox Name="myTextBox" Width="200" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,50,0,0"/>
        <Button Name="myButton" Content="Click Me" Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Click="MyButton_Click"/>
        <ComboBox Name="myComboBox" Width="120" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,150,0,0">
            <ComboBoxItem Content="Option 1"/>
            <ComboBoxItem Content="Option 2"/>
            <ComboBoxItem Content="Option 3"/>
        </ComboBox>
    </Grid>
</Window>

5. Implementing C# Code Behind

Let’s now add C# code to handle the button click event. Open the MainWindow.xaml.cs file and add code that displays the name when the button is clicked.


using System.Windows;

namespace MyWpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MyButton_Click(object sender, RoutedEventArgs e)
        {
            string name = myTextBox.Text;
            if (!string.IsNullOrEmpty(name))
            {
                MessageBox.Show("Hello, " + name + "!");
            }
            else
            {
                MessageBox.Show("Please enter your name.");
            }
        }
    }
}

6. Running the Application

Now press the F5 key to run the application. Enter a name in the input box and click the “Click Me” button, and a welcoming message will display with the entered name. This is an example of basic UI interaction in WPF.

7. Adding Various Controls

In this section, we will look at several additional controls available in WPF. This section explains how to add DataGrid, ListBox, CheckBox, and RadioButton.

Adding a DataGrid

The DataGrid is a control that is useful for displaying and editing large amounts of data. Let’s add a DataGrid as follows:


<DataGrid Name="myDataGrid" AutoGenerateColumns="False" Width="400" Height="200" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,200,0,0">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
        <DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
    </DataGrid.Columns>
</DataGrid>

Adding a ListBox

The ListBox displays a list of items and allows selection.


<ListBox Name="myListBox" Width="200" Height="100" HorizontalAlignment="Right" VerticalAlignment="Top">
    <ListBoxItem Content="Item 1"/>
    <ListBoxItem Content="Item 2"/>
    <ListBoxItem Content="Item 3"/>
</ListBox>

Adding a CheckBox

The CheckBox provides an option that users can select or deselect.


<CheckBox Name="myCheckBox" Content="Check me" Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,320,0,0"/>

Adding a RadioButton

The RadioButton allows users to select only one option among multiple choices.


<StackPanel Orientation="Vertical" HorizontalAlignment="Left" VerticalAlignment="Top">
    <RadioButton Name="option1" Content="Option 1" GroupName="Options"/>
    <RadioButton Name="option2" Content="Option 2" GroupName="Options"/>
</StackPanel>

8. Updated Full Code of the XAML File

The complete code of the MainWindow.xaml file including all the discussed controls is as follows:


<Window x:Class="MyWpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="400" Width="525">
    <Grid>
        <Label Content="Enter your name:" Width="120" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,10,0,0"/>
        <TextBox Name="myTextBox" Width="200" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,50,0,0"/>
        <Button Name="myButton" Content="Click Me" Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Click="MyButton_Click"/>

        <ComboBox Name="myComboBox" Width="120" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,100,0,0">
            <ComboBoxItem Content="Option 1"/>
            <ComboBoxItem Content="Option 2"/>
            <ComboBoxItem Content="Option 3"/>
        </ComboBox>

        <DataGrid Name="myDataGrid" AutoGenerateColumns="False" Width="400" Height="200" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,200,0,0">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
            </DataGrid.Columns>
        </DataGrid>

        <ListBox Name="myListBox" Width="200" Height="100" HorizontalAlignment="Right" VerticalAlignment="Top">
            <ListBoxItem Content="Item 1"/>
            <ListBoxItem Content="Item 2"/>
            <ListBoxItem Content="Item 3"/>
        </ListBox>

        <CheckBox Name="myCheckBox" Content="Check me" Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,320,0,0"/>

        <StackPanel Orientation="Vertical" HorizontalAlignment="Left" VerticalAlignment="Top">
            <RadioButton Name="option1" Content="Option 1" GroupName="Options"/>
            <RadioButton Name="option2" Content="Option 2" GroupName="Options"/>
        </StackPanel>
    </Grid>
</Window>

9. Data Binding

One of the powerful features of WPF is data binding. Data binding allows you to connect the UI with data, and when the data changes, the UI is automatically updated.

Creating a Model Class

First, let’s create a model class. Create a new class and set its name to Person.


public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Setting up the ViewModel

The ViewModel provides the data to be displayed on the UI. In the MainWindow.xaml.cs file, we will use ObservableCollection to manage the data.


using System.Collections.ObjectModel;

namespace MyWpfApp
{
    public partial class MainWindow : Window
    {
        public ObservableCollection<Person> People { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            
            People = new ObservableCollection<Person>();
            People.Add(new Person { Name = "Alice", Age = 28 });
            People.Add(new Person { Name = "Bob", Age = 32 });

            myDataGrid.ItemsSource = People;
        }

        private void MyButton_Click(object sender, RoutedEventArgs e)
        {
            string name = myTextBox.Text;
            if (!string.IsNullOrEmpty(name))
            {
                People.Add(new Person { Name = name, Age = 0 });
                myTextBox.Clear();
            }
        }
    }
}

10. Updating Data in the DataGrid

Now users can modify the data in the DataGrid, and the changes will be automatically reflected in the ObservableCollection. In the example, the user will add names to the list.

Conclusion

This post covered how to add and use various controls in WPF. We addressed basic UI components, data binding, and data management in the data grid, highlighting how to utilize the powerful features of WPF.

Next Steps

If you want to delve deeper into WPF, I recommend studying styles, templates, the MVVM pattern, asynchronous programming, and how to connect to databases. WPF has various possibilities, and you can create more attractive applications depending on your imagination.

In the next post, I will introduce how to create custom controls in WPF. Thank you!

This article was written by [Your Name].