Introduction to WPF in .NET Core

Introduction to WPF in .NET Core 1

Windows Presentation Foundation (WPF) is a new presentation framework to build visually aesthetic Windows desktop applications. The WPF framework allows a user to develop a rich user interface from the list of WPF framework features like XAML, media types, rich colors, animations, styles, templates, documents, text, and typography.

The WPF framework is build to take advantage of hardware acceleration of modern graphics cards enabling faster UI rendering, making it scalable, resolution-independent and supports vector rendering engine. In this blog post, we will look at the basic Introduction to WPF and take a look into its must-know features and they can be used as it is in NET Core 3.0 and above.

Table of Content:

  1. History of WPF
  2. Features of WPF
  3. WPF Architecture
  4. XAML – eXtensible Markup Language
  5. WinForms and WPF the basic differences
  6. Post Summary

History of WPF

Let us start the Introduction to WPF first by knowing its history, WPF version 3.0 was first released as a part of .NET Framework 3.0 in the year 2006 and received its major updates and enhancements in version 3.5 which was released with .NET Framework 3.5. The table below will give an overall timeline about the feature and updates that were added in subsequent major releases.

Year.NET Framework WPF VersionFeature Enhancement and Updates
20063.03.0Initial release as WPF 3.0
20073.53.5App model, data bindings, controls, documents, 2D and 3D elements
20083.5 SP1 3.5 SP1New WebBrowser control, Splash Screen, DirectX Pixel Shader support and performance improvement
20104.04.0DataGrid, DatePicker, Calender controls addition and MultiTouch enhancement
20124.54.5INotifyDataErrorInfo was added, useful in user input validation
20154.64.6High DPI and touch capabilities improvement
20174.74.7New APIs for Printing
20194.84.8Support for Per-Monitor V2 DPI Awareness and Mixed-Mode DPI scaling

Features of WPF

There are many great out of the box features offered by WPF, given below is the list of few important features that a WPF developer must be aware of.

XAML: XAML is the new way of creating UI in WPF. XAML code is declarative in nature and provides a way to separate UI logic from business logic and allowing separation of concerns. XAML maps to .NET objects and can be even created with various tools, the most popular being Blend for Visual Studio. More details about XAML in later sections.

Resolution Independent: The WPF applications are resolution independent and use a device-independent unit which is 1/96 of an inch. Based on the resolution WPF calculates the size of the UI controls on runtime. The framework uses vector-based graphics and uses DirectX for rending the UI elements which is very high performant and is scalable.

Templates: WPF makes it very easy to create shareable UI resources that can be reused to apply a consistent look and feel across the application. WPF provides two types of templates, Control Templates and Data Templates.

Control Template can be used to customized or define the appearance of the control. For example, if you want a button with a blue border and animation of clicking the same then we can define a control template for the button and use across the application.

Likewise, we have a Data Template to define the look and feel of the control that displays a list of objects. The template can be shared as a resource at the various application levels and helps in reusability.

Data Binding: This is one of the most powerful features of WPF and describes the relationship between UI context data and element property for displaying data. The feature allows declaratively to bind commands, key bindings, animation, binding update triggers, and other UI control events directly from the XAML code. WPF supports four-way of data binding as follows:

  • OneWay: This way of a binding set the data from the source to the target element. Any changes made to the source is updated on the target element whereas changes made to the UI element is not reflected back to the source.
  • TwoWay: This way of binding bidirectional between the source object and the target element. Any changes made on the source or target are reflected back on either side. This type of binding is mostly used on control accepting user inputs.
  • OneWayToSource: This is one-directional binding and the data from the target is updated on the source. Any changes made on the source object is not reflected back on the target.
  • OneTime: This is one time binding and the target is updated only for the first time when the target is initialized or the data context is updated. Any changes henceforth are not updated. This type of binding is mostly used to update the target with some static value. Like for example, displaying logged in user name on the UI.
  • Default: This is the default binding mode and depends upon the control using it. Like for example, Textbox uses TwoWay binding as it accepts text from the user and the same can be used to display text from the data context of the UI.

Style: WPF allows styling the appearance of its UI controls through its Style property. Style accepts a collection of the property-value set that can be applied to the control. The Style can be shared as a resource and reused for multiple controls. Style can be used to change all visual characteristics like margin, padding, font color, size, etc. The Style can also be applied or changed on runtime based on the control triggers providing a very dynamic user interface.

Animation: This is another core feature of WPF and provides a way to create a dynamic user interface. Many properties of WPF can be animated. The framework support timer and property-based animation. Using animation on control can help the user interface look more intuitive and responsive. Just like templates and Style, Animation can be shared as a resource and can be reused throughout the application.

3D: WPF milcore directly interacts with the Direct3D engine to render the user interface and utilize GPU acceleration, thus delivering high-performance rendering. Using WPF complex 3D objects can be build using XAML and provides hit-testing, mouse-based rotation, and other 3D basic functionality.

Document: The WPF provide a wide range of document features to create and display a large amount of content in an organized way that they are easy to read without worrying about the display area. WPF currently supports two types of documents:

  • Fixed Document: As the name suggests, the position of the content of this type of document is fixed and are print-ready documents. A typical use of fixed format is in desktop publishing, word processing, etc.
  • Flow Document: The content of this Flow document is not tied to any fixed location and it best used for optimized content viewing and readability. The Flow document dynamically adjusts the content based on screen availability.

WPF Architecture

WPF is designed as a Multilayer architecture. At the top of the stack is placed the top-level managed services written in C# language. Second, in the stack is the Media Integration Layer (MIL) or the milcore in short and is the unmanaged code. Last to the layer is the core operating systems APIs that help in the process management of the WPF application. Let us discuss each component that makes up these layers.

Introduction to WPF - WPF Architecture
WPF Architecture

Managed Layer: The layer is composed of three different services:

  • PresentationFramework.dll: This DLL provides the basic types to build a WPF application, such as windows, controls, shapes, media, documents, animation, data bindings, style and many more.
  • PresentationCore.dll: This DLL provides basic types like UIElement and Visual. The UIElement defines the actions and element layout properties and provides classes to override them if required. The Visual class provides the element rendering functionality and create the Visual Tree containing description about rendering the element.
  • WindowBase.dll: This DLL holds the WPF basic types like DependencyProperty, DependencyObject, DispatcherObject, and other types. The important one is given below:
    • DependencyProperty provides a new property system that can enable or disable function like data binding, define attach properties, etc.
    • DependencyObject is the base of every WPF types and provides the function to enable property notification.
    • DispatcherObject: This class provides a way for thread safety and threads other than Dispatcher created cannot directly access it.

Unmanaged Layer: This layer consist of two different services.

  • Milcore.dll: This is the media integration library or milcore that provides direct interaction with the DirectX and renders all the UI elements through this engine.
  • WindowsCodecs.dll: This DLL provides the services for imaging like displaying, scaling, etc.
  • Direct3D: This DLL provides access to low-level API which helps in rendering in WPF.
  • User32: This is the basic core OS functionality that every application on Windows uses.

Basic Class Hierarchy of WPF Types

Moving on with the introduction to WPF, in this section of the post, we will discuss the most important basic types of WPF, knowing them and their hierarchy comes really handy while programming. Let us briefly look into them below:

Introduction to WPF - Class Hierarchy
Class Hierarchy

DispatcherObject: WPF application uses Single-Thread Affinity (STA) model and therefore every UI element are owned by a single thread. This is the only thread that Dispatcher was created to have access to DispatcherObject directly. If other threads want to access DispatcherObject then need to call Invoke or BeginInvoke services provided by the Dispatcher with the DispatcherObject associated with it. All the objects that derive from DispatcherObject have thread affinity and can verify if the correct thread is accessing the values. This class is a part of “System. Threading” namespace.

DependencyObject: WPF introduced a new property system called the Dependency Property having features like change notification, support data bindings, attached properties, etc. DependencyObject represents the object that participates in this new property system. The DependencyObject helps to enable new features of this property system on the object itself. A few of the services and features that can be enabled are, enabling property change notification, registering dependency property into the WPF property system, metadata, coerce value support, enabling attached properties, etc. This class is a part of “System. Windows” namespace.

Visual: This is another very important class that provides rendering support in WPF. All the user interface controls like Button, ListBox derive from this class. The Visual class defines all the properties required for rendering, clipping, transforming, bounding and hit test. This class is also an interface between the managed code and unmanaged milcore layer that renders the element. The class helps in constructing the Visual Tree containing the element rendering properties values. The class is a part of “System.Windows.Media” namespace.

UIElement: This class adds the basic functionality of layout, input, focus, and events to UI elements and sets the basic foundation of the layout process. Event for keyboards, mouse, stylus input and related status properties are added by this class. These events are raised as routed events (new events in WPF) and traverse bubbling and tunneling pair techniques across the elements. This class also provides major services like data binding, style, and animation as well as support for commands. This class is a part of “System. Windows” namespace.

FrameworkElement: This class extends the functionality provided by the UIElement, and override layout for framework level implementations. The support for the Logical Tree is provided by this class and the markup that define this tree is also defined in this class. The FrameworkElement defined events related to object lifetime and provided hooks for implementing the code behind. The class defines the support for Style and implements BeginStoryboard and its members for WPF animation. This class is a part of “System. Windows” namespace.

Shape: This class is the base class for shape elements like Line, Ellipse, Polygon, Path, etc. The class can be found in the “System.Windows.Shapes” namespace.

Control: This namespace contains all the elements that help in interacting with the user. Few of the control like Textbox, Button, Listbox, Menu, etc are present in this namespace. Font, Background color and control appearances support via templates support are added from this namespace.

ContentControl: This is the base class for all the control that supports only single content. Control from Label, Button, Windows, etc all support single content only. The content can be anything common language runtime object from a combination of various control, DateTime object to a simple string. The appearance of the control can be enhanced using a data template. This class can be found in the “System.Windows.Controls” namespace.

ItemsControl: This is the base class for all the control that displays a list of items and includes controls like, ListBox, TreeView, Menus, Toolbar, etc. ControlTemplate can be used to change the appearance of the control and ItemsTemplate can be applied to define how the objects will be displayed on the control. This class is present in the “System.Windows.Controls” namespace

Panel: This class is the base class of all the layout container elements. The class can host child objects and provides service to position and arrange child objects in the user interface. Control like Grid, Canvas, DockPanel, StackPanel, WrapPanel, etc derives from this class. This class can be found in the “System.Windows.Controls” namespace.

XAML – eXtensible Markup Language

Introduction to WPF cannot be completed without discussing XAML. XAML stands for eXtensible Markup Language and is an XML based language that can be used to create and initialize .NET Objects. XAML is an independent language that can be used in many different areas but primarily used in creating a WPF user interface. The user can create the WPF application without using XAML directly through the C# code, but using XAML is the recommended way.

The use of XAML provides a separation of concerns and helps in separating the UI creation and business logic development. The UI designer can use the separate tool “Blend for Visual Studio” for creating and designing the user interface and the developer can work on Visual Studio independently to implement the business logic. Blend provides drag and drop of control with an easy to use the designer to create the UI. WPF project can be opened in Blend as well as Visual Studio seamlessly.

XAML can be used for performing many tasks, below are the few important ones:

  • User Interface: XAML can be used to create user interface elements declaratively.
  • Event Handlers: The most common task in creating an application is to wire up the UI elements event to handler like, the famous one is the button click event. The user can attach these handlers from XAML.
  • Resource: Common resources can be declared at various levels in the XAML code and can be reused in the XAML hierarchy. The resource allows us to centralize common XAML code and allows reusability.
  • Control Templates: WPF controls are all skinless control, all the default control has standard looks, and this is can completely be customized or recreated using ControlTemplate. They are also a type of resource and can be reused, for example, if you want to make a round button with the red border you can define the control template at the application level and reused it for all button used in the application providing a consistent look for the UI.
  • Data Templates: Just like Control Templates, Data Templates can also be defined using XAML to provide a consistent look for displaying a list of items. Data Templates can also be declared as a resource and can be used throughout the application.
  • Data Binding: The relationship between the element and the context data can be defined in XAML using XAML markups. This relationship defines how the data is displayed on the user interface.
  • Animation: Animation used by various controls can be defined in the XAML code and can be shared across the application when shared as a resource.

Sample XAML for creating a Label having HorizontalAlignment and VerticlAlignment value as the center, FontSize as 20 and content as “Hello XAML”

  <Window x:Class="WpfAppCore.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Label HorizontalAlignment="Center" 
               VerticalAlignment="Center"
               FontSize="20"
               Content="Hello XAML"/>
    </Grid>
</Window>

WinForms and WPF the basic difference:

#WinFormsWPF
1Windows Form is there for a quite long time and is tried and tested over time.WPF is relatively a new framework and adheres to new UI standards.
2There are plenty of third-party controls and extensive documentation is available.As WPF is fairly new, third-parties control support is added every now and then. Whereas WPF controls can be extended or build as per requirement very easily.
3Windows Form has a designer code attached to the form.WPF uses XAML for designing the UI and offers separation of concerns.
4Unit testing is quite hard.As WPF views are separate from business logic, unit testing is quite easy.
5Windows Form is less scalable than WPF.WPF uses GPU hardware acceleration and uses the DirectX engine to render the UI.
6Windows Form controls are resolution-dependent.WPF uses a device-independent unit and does not depend upon system resolution.
7Windows Form being older framework is less secure than WPF.WPF is a new framework and is designed to be more secure than WinForms

Summary:

  • WPF (Windows Presentation Foundation) is a new presentation framework by Microsoft and was first released with NET Framework 3.0.
  • WPF uses a device-independent unit and the UI is resolution-independent.
  • WPF is a multilayer architecture having managed and unmanaged code.
  • WPF uses XAML to build the user interface and external tools like Blend for Visual Studio can be used to design and generate XAML code.
  • WPF introduces a new and powerful property system called Dependency Property
  • WPF introduces a new event routing mechanism compared to WinForms called the RoutedEvents allowing the event to tunnel or bubble through the Visual Tree.
  • WPF uses vector-based graphics rendering which is faster and highly scalable.
  • WPF uses GPU and uses the DirectX engine to render the user interface.
  • WPF provided look less control having standard templates attached to them.
  • Control Templates can be used to change the look and feel of control.
  • Data Templates can be used to change the appearance of control displaying a list of objects.
  • WPF elements can be hosted in WinForms and vice versa.
  • WPF can host complex 2D and 3D objects.
  • WPF supports various media types.
  • WPF provides Document API for building two types of documents, the Fixed document, and the Flow document.

This concludes the post Introduction to WPF, I hoped the article helped you in understanding the basic concept and architecture of WPF. Thanks for visiting, Cheers!!!

[Further reading: How to create WPF application using dotnet-cli | Top 7 must-have Visual Studio 2019 extensions | AI vs ML vs DL – The basic differences | Top 5 Machine Learning Frameworks to learn in 2020 | Publishing Single Executable (EXE) in NET Core 3.0 | Visual studio 2019 Code Navigation using Ctrl+T ]

External download link:

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments