WPF (Windows Presentation Foundation) is a powerful GUI (Graphical User Interface) development platform that is part of the .NET Framework. One of the main advantages of WPF is its support for data binding, 2D/3D graphics, video, and visual effects, allowing developers to focus on enhancing user experiences through these diverse features. In this article, we will explore the basic controls of WPF in detail and provide simple example code to lay the foundation for WPF development.
1. Understanding WPF Controls
The controls used in WPF are UI components that can handle various user interactions. These controls play a crucial role in how users interact with applications and mainly include the following types:
- Basic Controls: Button, TextBox, Label, etc.
- Layout Controls: Grid, StackPanel, WrapPanel, etc.
- Input Controls: ComboBox, ListBox, CheckBox, RadioButton, etc.
- Selection Controls: Slider, ProgressBar, etc.
- Tree and Grid Controls: TreeView, DataGrid, etc.
2. Using Basic Controls
Using the basic controls in WPF is the first step in constructing the application UI. Each control is declared in XAML (Extensible Application Markup Language) code and can be controlled through C# code. Let’s take a look at the most basic controls: Button, TextBox, and Label.
2.1 Button Control
The Button is a basic control that can handle user click events. It can be implemented to perform specific actions upon clicking. Below is a simple example of the Button control.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Button Example" Height="200" Width="300">
<Grid>
<Button Name="myButton" Content="Click Here" Width="100" Height="30" Click="myButton_Click"/>
</Grid>
</Window>
In the above code, the Button has the text “Click Here,” and when the Click event occurs, the C# method myButton_Click is called. Below is the C# code that handles this.
using System.Windows;
namespace WpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void myButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("The button has been clicked!");
}
}
}
2.2 TextBox Control
The TextBox is a control that allows users to input text. It is useful for receiving and processing user input. Below is an example that combines a TextBox and a Button to take user input and output it to a message box.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF TextBox Example" Height="200" Width="300">
<Grid>
<TextBox Name="myTextBox" Width="200" Height="30" Margin="10"/>
<Button Content="Confirm Input" Width="100" Height="30" Margin="10" VerticalAlignment="Bottom" Click="myButton_Click"/>
</Grid>
</Window>
The C# code that outputs the content entered in the TextBox to a message box when the button is clicked is as follows.
private void myButton_Click(object sender, RoutedEventArgs e)
{
string userInput = myTextBox.Text;
MessageBox.Show($"Input content: {userInput}");
}
2.3 Label Control
The Label control is primarily used to display text. Unlike other controls, it cannot be clicked for user interaction. Labels are useful for providing information about UI elements. Below is an example of using a Label together with a TextBox.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Label Example" Height="200" Width="300">
<Grid>
<Label Content="Please enter your name:" Margin="10"/>
<TextBox Name="nameTextBox" Width="200" Height="30" Margin="10,30,10,10"/>
<Button Content="Confirm" Width="100" Height="30" Margin="10,70,10,10" Click="checkButton_Click"/>
</Grid>
</Window>
The C# code when the button is clicked is as follows.
private void checkButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show($"Entered name: {nameTextBox.Text}");
}
3. Layout Controls
To effectively arrange various basic controls, WPF provides several types of layout controls. Here, we will explore Grid, StackPanel, DockPanel, and WrapPanel.
3.1 Grid
The Grid is one of the most useful layout controls, creating a two-dimensional grid layout composed of rows and columns. When placing controls in the grid, you can specify the Row and Column to place the controls exactly where you want them.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Grid Example" Height="200" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Content="Name:" Grid.Row="0" Grid.Column="0"/>
<TextBox Name="nameTextBox" Grid.Row="0" Grid.Column="1"/>
<Button Content="Confirm" Grid.Row="1" Grid.ColumnSpan="2" Click="checkButton_Click"/>
</Grid>
</Window>
In the above example, the rows and columns are defined, and the placement of each control is specified. You can customize the layout using RowDefinition and ColumnDefinition.
3.2 StackPanel
The StackPanel is a simple layout control that stacks child elements either vertically or horizontally. You can easily set the orientation using the Orientation property, as shown in the code below.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF StackPanel Example" Height="200" Width="300">
<StackPanel Orientation="Vertical">
<Label Content="Name:" />
<TextBox Name="nameTextBox" />
<Button Content="Confirm" Click="checkButton_Click" />
</StackPanel>
</Window>
StackPanel offers a simple structure that allows for quick UI construction.
3.3 DockPanel
The DockPanel is a layout control that allows child elements to dock to each position on the screen. Each child element can dock to the Top, Bottom, Left, Right, and the last element will occupy the remaining space.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF DockPanel Example" Height="200" Width="300">
<DockPanel>
<Button Content="Top" DockPanel.Dock="Top" Click="checkButton_Click" />
<Button Content="Bottom" DockPanel.Dock="Bottom" Click="checkButton_Click" />
<Button Content="Left" DockPanel.Dock="Left" Click="checkButton_Click" />
<Button Content="Right" DockPanel.Dock="Right" Click="checkButton_Click" />
<Button Content="Center" Click="checkButton_Click" />
</DockPanel>
</Window>
The DockPanel allows for flexible layout configurations by placing elements in various directions.
3.4 WrapPanel
The WrapPanel is a layout control that stacks child elements horizontally and automatically wraps to the next line when space runs out. It’s useful when dealing with a large number of items.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF WrapPanel Example" Height="200" Width="300">
<WrapPanel>
<Button Content="Button 1" Width="80" />
<Button Content="Button 2" Width="80" />
<Button Content="Button 3" Width="80" />
<Button Content="Button 4" Width="80" />
<Button Content="Button 5" Width="80" />
<Button Content="Button 6" Width="80" />
</WrapPanel>
</Window>
The WrapPanel is particularly useful for flexibly placing a large number of buttons or icons.
4. Input Controls
WPF provides a variety of input controls to capture user selection. We will look at input controls like ComboBox, ListBox, CheckBox, and RadioButton.
4.1 ComboBox
The ComboBox is a control that allows the user to select an item from a dropdown list. It is useful because it provides options that users can also input themselves. Below is an example using a ComboBox.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF ComboBox Example" Height="200" Width="300">
<Grid>
<ComboBox Name="myComboBox">
<ComboBoxItem Content="Option 1"/>
<ComboBoxItem Content="Option 2"/>
<ComboBoxItem Content="Option 3"/>
</ComboBox>
<Button Content="Confirm Selection" Click="myButton_Click" Width="100" Height="30" Margin="0,50,0,0"/>
</Grid>
</Window>
The C# code that outputs the selected item is as follows.
private void myButton_Click(object sender, RoutedEventArgs e)
{
if (myComboBox.SelectedItem is ComboBoxItem selectedItem)
{
MessageBox.Show($"Selected option: {selectedItem.Content}");
}
}
4.2 ListBox
The ListBox is a control that displays several items and allows the user to select one item of their choice. It can show selectable items in a list format. Below is an example using a ListBox.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF ListBox Example" Height="200" Width="300">
<Grid>
<ListBox Name="myListBox">
<ListBoxItem Content="Item 1"/>
<ListBoxItem Content="Item 2"/>
<ListBoxItem Content="Item 3"/>
</ListBox>
<Button Content="Confirm Selection" Click="myButton_Click" Width="100" Height="30" Margin="0,50,0,0"/>
</Grid>
</Window>
The C# code to check the selected item from the ListBox is as follows.
private void myButton_Click(object sender, RoutedEventArgs e)
{
if (myListBox.SelectedItem is ListBoxItem selectedItem)
{
MessageBox.Show($"Selected item: {selectedItem.Content}");
}
}
4.3 CheckBox and RadioButton
The CheckBox allows users to select one or more options among several, while the RadioButton allows users to select only one option among several. Below are examples of using these two controls.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF CheckBox & RadioButton Example" Height="200" Width="300">
<StackPanel>
<CheckBox Name="checkBox1" Content="Option 1"/>
<CheckBox Name="checkBox2" Content="Option 2"/>
<RadioButton Name="radioButton1" Content="Single Select 1"/>
<RadioButton Name="radioButton2" Content="Single Select 2"/>
<Button Content="Confirm" Click="checkButton_Click" />
</StackPanel>
</Window>
The C# code to check the selected options is as follows.
private void checkButton_Click(object sender, RoutedEventArgs e)
{
string checkedItems = $"Selected CheckBox: {(checkBox1.IsChecked == true ? checkBox1.Content : "")} {(checkBox2.IsChecked == true ? checkBox2.Content : "")}";
string selectedRadio = radioButton1.IsChecked == true ? radioButton1.Content.ToString() : radioButton2.Content.ToString();
MessageBox.Show($"{checkedItems}\nSelected RadioButton: {selectedRadio}");
}
5. Events and Data Binding
In WPF, events are used to handle user interactions, and data binding allows for the synchronization between UI and data. This facilitates simpler communication between the visual interface and the data. The following example demonstrates a simple data binding process.
5.1 Data Binding
Data binding is one of the core features of WPF, enabling the automatic reflection of changes in data to the UI by connecting UI elements to data sources. Below is an example of data binding using ListBox and TextBlock.
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Data Binding Example" Height="200" Width="300">
<StackPanel>
<ListBox Name="myListBox" SelectedItem="{Binding SelectedItem}" />
<TextBlock Text="{Binding SelectedItem, ElementName=myListBox}" />
</StackPanel>
</Window>
By creating a ViewModel and setting up the data to bind, the selected item from the ListBox will automatically appear in the TextBlock.
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
namespace WpfApp
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
public ObservableCollection Items { get; set; }
private string _selectedItem;
public string SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
public MainWindow()
{
InitializeComponent();
Items = new ObservableCollection { "Item 1", "Item 2", "Item 3" };
DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Conclusion
WPF is a platform for creating powerful UI applications through a variety of basic controls, layout controls, and data binding features. This article introduced the simple controls of WPF and provided examples of how each control can be utilized. By exploring and leveraging the diverse features of WPF, including basic controls, you can develop applications that provide a richer user experience. Continuous exploration and practice of WPF will enable you to create more sophisticated applications.
I hope this article assists you in WPF development. Familiarize yourself with the characteristics and usage of each control, and gain a deeper understanding through practice. Wishing you success on your journey of WPF development!