DEV Community

Cover image for The Definitive Guide to WPF Controls
Chelsea Devereaux for MESCIUS inc.

Posted on • Originally published at Medium

The Definitive Guide to WPF Controls

WPF (Windows Presentation Foundation) is a modern .NET development framework for creating software applications that run on Windows Operating Systems. WPF provides a comprehensive set of application-development features that include UI controls, data binding, 2D and 3D graphics, animation, templates, documents, media, and more.

One of the key differences between WPF and its predecessor, Windows Forms (or WinForms), is the approach used to design the user interface and control templates. In this article, we examine everything about WPF controls, from standard availability to advanced customization.

WPF versus WinForms

WinForms was the preferred option for developing a desktop Windows application until .NET 3.0 when Microsoft added WPF to the .NET stack of frameworks. WPF added many improvements, including better data binding, styling, and performance enhancements. At the time of this writing, WPF is still the preferred Windows desktop development platform with .NET 9.0, as Microsoft announced new WPF features at Microsoft Build 2024.

WPF takes advantage of modern 2D and 3D graphics hardware, allowing Windows applications to more easily offload some graphic tasks to the GPU using DirectX rendering. This makes WPF the preferred framework for applications that need to focus on animations, styles, and media.

What is XAML?

One of the key differences of WPF is how developers create user interfaces. WPF was the first .NET platform to use XAML (eXtensible Application Markup Language) as the syntax for defining user interfaces. The application logic is still written in C# or VB.NET code, just like WinForms, but the declarative nature of XAML allows interfaces to be developed and designed in a straightforward approach. XAML works very similarly to HTML, allowing easy and responsive layout definitions.

WPF Controls Overview

WPF controls are reusable design elements that help developers implement a wide variety of features. You can think of a control toolbox like a box of Lego pieces that you use to build the application. UI controls include common software UI elements like buttons, text boxes, date pickers, toolbars, menus, lists, images, and much more.

Controls have an API (application programmable interface) that lets you configure how the control will work for your specific application. Consider a Button control, for example. It has a “Content” property, which can be set to what text you want displayed on the button. It also has size properties like “Width” and “Height.” It also has events triggers when actions occur, such as a “Clicked” event that fires when the user clicks the button. Complex controls have richer APIs.

Standard WPF Controls

The base controls included with .NET itself are often known as “standard” or “basic” controls. They are part of the base .NET libraries. Standard .NET WPF controls typically fall into four main categories: input, layout, data, and media (note: these groupings are unofficial and somewhat subjective).

Below is a table containing the standard WPF controls.

WPF controls

Let’s take a look at some common WPF control examples.

WPF Input Controls

Input controls are used to collect input from the user such as clicking and text-based input. The standard WPF controls include most basic input controls you need to create a rich data entry form. Each input control supports a “Value” or similar property representing the input value, which can be retrieved from code or through two-way data binding (read more on data binding in the MVVM section).

ComboBox example:

<ComboBox MinWidth="200" HorizontalAlignment="Left" ItemsSource="{Binding FontSizes}" SelectedIndex="0" IsEditable="True" />
Enter fullscreen mode Exit fullscreen mode

WPF Layout Controls

Layout controls define the arrangement of their child elements. They are essentially containers that each have unique rules on how to arrange the controls contained within them. The WPF standard controls include almost all the typical layouts you would ever need, including:

  • Grid — arranges children into rows and columns
  • StackPanel — arranges children in a single horizontal or vertical row
  • WrapPanel — arranges children horizontally (or vertically) until they fit and creates additional rows (or columns) to fit all the children
  • DockPanel — arranges children along the edges of the container, with undocked children taking up the remaining space in the middle
  • Canvas — arranges children using absolute positioning (basically how WinForms positioned controls)

Grid example:

<Grid Margin="10">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition />
    </Grid.RowDefinitions>
    <TextBlock Text="My WPF Application" FontSize="36" Grid.Row=1 Grid.ColumnSpan="2" />
</Grid>
Enter fullscreen mode Exit fullscreen mode

There are other layout-related controls, including Borders, Shapes, ScrollBars, and Splitters, which help enhance the visual aspect of the layout. The Window control acts as the application’s frame.

WPF Data Controls

Data controls are used for visualizing and binding to collections of data. The DataGrid is used to display and edit tabular data, and the ListView is a more straightforward bound list control. Unlike WinForms, WPF does not include charts besides the handy little ProgressBar.

The DataGrid control is often the central and most powerful part of the application, providing the most data-centric functionality in one control. Users can view, edit, and analyze their data with one powerful control. The standard WPF DataGrid control supports basic functions like data binding, sorting, cell formatting, column reordering, selection, grouping, and row details.

WPF DataGrid

WPF DataGrid control

Since WPF does not include many data-bound controls, you may consider adding some third-party controls like the FlexGrid. Third-party WPF controls extend the common ones with more features and styles as well as expand the toolbox to include many more.

Pinning

WPF FlexGrid Datagrid Control

WPF Media Controls

Media controls are used to display files such as images, videos, and documents. With WPF, you can more easily display high-quality video and audio files in your desktop application using the MediaElement.

MediaElement example:

<MediaElement Source="media/numbers-aud.wmv" />
Enter fullscreen mode Exit fullscreen mode

How to Get Started with Standard WPF Controls

The best place to start learning is the new WPF Gallery Preview app in the Windows Store. Microsoft created this as a one-stop resource for learning about the WPF UI tools and control features. This developer tool demonstrates WPF controls and styles for .NET 9 and onwards.

Gallery Preview

WPF Gallery Preview Windows App

Continue reading this blog to expand on topics like styles and data binding.

Custom WPF Controls

Additional controls and features can be achieved by customizing the standard controls or personally creating new controls. WPF features a built-in architecture for creating custom controls more easily than with WinForms due to XAML. You can customize existing controls in two ways: with Styles and Templates. You can create your own custom controls with User Controls or license production-ready third-party controls from the community. Let’s look closer at each of these areas.

How to Customize Standard Controls with Styles and Templates

One of the great features of WPF and other XAML frameworks is Styles. Styles allow us to create reusable, encapsulated sets of properties for any UI element. For instance, a Style can be used to customize the appearance of Buttons across your entire application. Plus, implicit and explicit styles allow you to manage the styling scope further.

  • An implicit style has no “Key” set, so it will apply to every targeted UI element within its scope.
  • A Style defined within a Window has a scope of just that Window.
  • A Style defined within the App.xaml file has an application-wide scope.

Example:

It’s recommended to put styles in your App.xaml file so every form and window in the application can access it if necessary. This example creates a Style to create red buttons.

<Application x:Class="TestWpfDemoApp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:TestWpfDemoApp"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Style x:Key="RedButtonStyle" TargetType="Button">
            <Setter Property="Background" Value="Red" />
        </Style>
    </Application.Resources>
</Application>
Enter fullscreen mode Exit fullscreen mode

Then, throughout your UI, you can reference the style like this:

<Button Content="Button 3" Style="{StaticResource RedButtonStyle}"/>
Enter fullscreen mode Exit fullscreen mode

If you remove the Key, the style will automatically apply to every button!

Styles are limited to the public API of the UI control. To customize beyond that, you must customize the control template. For example, the WPF Button control is limited to appearing as a rectangle. If you wish to create a circular button, you could create a User Control, which we’ll discuss next, or customize the Button’s control XAML template.

To learn more about customizing the control templates, see How to Create a Template for a Control (WPF.NET).

How to Create Custom User Controls

Visual Studio includes a UserControl (WPF) file template that can be used to create a reusable, custom control. A user control can be composed of standard controls. You could use it to create a data entry form that’s used several times in the application, or you can use it to create a custom control.

User control

WPF includes several primitive elements that help create custom elements. For example, you could create a user control with an Ellipse and a TextBlock to create a round button.

Round button

You can reference your custom user controls throughout your application using the “local” XML namespace.

LocalXmlns

Third-Party WPF Controls and Components

Microsoft made the .NET frameworks extensible, allowing developers to extend the capabilities of their own applications further. Third-party control suites typically fill the gap by adding essential UI controls that are missing from the basic set (like charts!), as well as providing more built-in features for datagrids and input controls.

While you may find some free WPF controls on GitHub, Microsoft also has a Community Toolkit that provides additional controls like InkCanvas and Maps. You can even invest in professionally developed UI controls from companies like DevExpress, MESCIUS (formerly GrapeCity), Progress (formerly Telerik), and SyncFusion. Unlike most free control suites, these come with complete samples and documentation and are regularly updated and tested. You can save a lot of development time by licensing a third-party WPF control suite rather than implementing those custom controls independently.

Top Custom WPF Controls

Since we can’t possibly list every third-party WPF control, we will share what we consider to be some of the most useful ComponentOne WPF controls.

WPF Chart Controls

Since charts are not included in the standard toolbox but are essential for business applications and dashboards, they are a very useful control to license from a control vendor. Plus, they are complex and difficult to write from scratch independently. For example, the ComponentOne FlexChart package includes 2D WPF charts that support all common chart features with high-performing Direct2D rendering.

FlexChart Showcase

WPF FlexChart Control

WPF Reports and PDF Libraries

The standard WPF controls include basic document generation and XPS support. That’s fun, but what you really need is a powerful report generator and PDF viewer. These features are commonly found in custom, off-the-shelf libraries such as FlexReport and FlexViewer.

FlexViewer

WPF FlexViewer Control

WPF DataGrid Controls

The WPF .NET DataGrid control provides most of the basic features you need, but what it really lacks is an elevated design. It requires a lot of customization to achieve a modern, fluent design. A more attractive and powerful WPF datagrid control is the FlexGrid datagrid control. The benefits of using a third-party datagrid, like FlexGrid, are better performance, more themes, and more built-in features like column and row freezing, cell merging, and transpose views.

FlexGrid

WPF DataGrid (left) and ComponentOne FlexGrid (right)

WPF Scheduler Controls

When it comes to data and time editing and event scheduling, the standard WPF controls only include simple editors and a calendar. Building a custom scheduler as rich as Microsoft Office is a tall order, so this is a great use case for licensing third-party components. This C1Scheduler WPF control provides month, week, day, and timeline views along with complete Outlook-style appointment editing dialogs.

Scheduler

WPF Scheduler Control

WPF Docking Controls

Desktop applications often include many tabs and panels, making the user interface complex. Your favorite productivity tools, like Adobe Premiere, Adobe Photoshop, and Visual Studio, utilize docking tabs that allow end-users to rearrange their personal workspaces. This is another library that would be quite complicated to implement using only the WPF TabControl. The C1DockControl for WPF provides two different docking experiences from which you can choose.

Dock Control

WPF DockControl

How to Add WPF Controls to Your .NET Applications

Windows Forms provides one of the most productive ways to create desktop apps based on the visual designer provided in Visual Studio.

How to Add Standard Controls Through the Designer

UI controls can be added to a XAML file by dragging and dropping them from the toolbox. First, let’s start by creating the .NET WPF application that targets .NET 9.

  1. Open Visual Studio (you can use the free Visual Studio community).
  2. Create a new “WPF App” project.
  3. Select .NET 8 (Long Term Support) as the Target Framework.
  4. Open the default MainWindow.xaml file.

Drag and drop some buttons and other controls to test it out. Note that some controls can be nested in others by declaring them within the tags of the parent. This is known as the Content of the parent control. Some controls only allow a single child as its Content, but you can work around this by creating a single layout control (such as a Grid) as the content and then placing many controls within the Grid.

How to Add Third-Party WPF Controls

Third-party WPF controls are also added to the UI from the toolbox, but first, we must add them to the toolbox. There are two methods for adding third-party controls to the toolbox: DLL reference and NuGet package.

  • DLL Reference — This is the original approach and can be used if you’ve downloaded a library assembly file (dll) for your third-party control. Right-click the toolbox and select “Choose Items…”. From there, you can browse and locate your library.
  • NuGet Package — This is the preferred way to work with all .NET 5+ components. Under the Visual Studio “Tools” menu, you can launch the “NuGet Package Manager” for the solution. Then, browse for your library from the public nuget.org source or any custom source. Once the package is installed, the controls within it will appear in your toolbox.

The major difference between these approaches is that adding the DLLs to the toolbox does not add them to the project. The control must be dropped to the design surface for the project reference to be added. By using the NuGet package, you are adding the project reference first.

Design Time

Data Binding with MVVM Design Principles

MVVM (Model-View-ViewModel) is a popular code architecture that takes advantage of WPF’s data binding capabilities. Once you begin any WPF development, you probably won’t escape the discussion surrounding MVVM, as it is widely regarded as one of the best practices.

In a nutshell, following MVVM simply means that all business logic (C# code) is separated into your ViewModel and Model C# files and not tightly tied to your UI code. Maintaining this clean separation between application logic and the UI helps address many different development issues and makes an application easier to test, maintain, and scale.

MVVM

The Model is really just the data schema that defines each business object.

Model example:

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    ...
}
Enter fullscreen mode Exit fullscreen mode

The View Model is essentially the data model that includes all the business logic directly related to the UI View. Note how the data is initially loaded — this may vary for real applications.

ViewModel example:

internal class MainViewModel : INotifyPropertyChanged
{
    private List<Product> _products;
    public List<Product> Products {
        get
        { 
            if(_products == null)
            {
                LoadData();
            }
            return _products;
        }
    }

    private async Task LoadData()
    {
        _products = await Northwind.LoadProductsAsync();
        NotifyPropertyChanged("Products");
    }

    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property.  
    // The CallerMemberName attribute that is applied to the optional propertyName  
    // parameter causes the property name of the caller to be substituted as an argument.  
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
Enter fullscreen mode Exit fullscreen mode

The View is our XAML UI. Note that a key piece to this puzzle is the DataContext. Every WPF UI element, including the Window itself, features a DataContext property.

View example:

<Window
        ...
        xmlns:local="clr-namespace:TestWpfDemoApp"
        xmlns:c1="http://schemas.componentone.com/winfx/2006/xaml" 
        Title="My WPF App" Height="450" Width="800">
    <Window.DataContext>
        <local:MainViewModel />
    </Window.DataContext>
    <Grid>
        <c1:FlexGrid ItemsSource="{Binding Products}"/>
    </Grid>
</Window>
Enter fullscreen mode Exit fullscreen mode

Conclusion

WPF was released with .NET 3.0 as a potential replacement for WinForms. To this day, both platforms remain viable solutions for developing .NET desktop applications. The main difference is that WPF components are implemented using XAML, which makes it easier to implement data binding and customize the UI appearance.

XAML Facilitates Easier Data Binding

WPF (and other XAML-based frameworks, like WinUI) allow you to set properties and data binding directly in the markup. WPF is typically considered more MVVM-friendly as data binding is very straightforward, thanks to the DataContext concept. This makes it very easy to separate UI logic from business logic.

<Window ...>
    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
    <Grid>
        <DataGrid x:Name="dataGrid" ItemsSource="{Binding Forecasts}"/>
    </Grid>
</Window>
Enter fullscreen mode Exit fullscreen mode

XAML Makes It Easy to Customize Appearance

XAML-based components are inherently more customizable with styles and control templates. Styles are a great way to create a unified appearance across your application. If you need to customize a WPF UI control further, you can customize its XAML template, which is generally considered a step easier than overriding WinForms renderers but still not the easiest task for an average developer.

Themes

WPF UI Controls with Custom Styles

Many third-party libraries offer a rich API for appearance customization that saves a lot of development time. ComponentOne WPF controls provide extensive Brush and Color properties, customizing the appearance of controls without the need for themes or custom templates. Plus, certain built-in themes, like Google’s Material and Microsoft Office-inspired themes, are provided.

Top comments (0)